為了要讓蘋果被蛇吃掉後,隨機生成在遊戲畫面內,我們要在hierarcky中創立新的物件foodarea,也要幫foodarea加上collider,不過這次是選box collider,不是circle collider,然後要記得調整大小
打開先前創好的apple腳本,並輸入這段程式碼:
using UnityEngine;
public class Apple : MonoBehaviour
{
public Collider2D foodarea;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnEnter2D(Collider2D collision)
{
Debug.Log(collision);
}
}
回到unity後,把左邊hierarcky的foodarea拉到剛剛在apple inspector裡的foodarea中
接著又要回到前面的apple腳本,並輸入這段程式碼:
using System.ComponentModel;
using UnityEngine;
public class Apple : MonoBehaviour
{
public Collider2D foodarea;
void Start()
{
RandomPosition();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(collision);
Debug.Log(foodarea.bounds.min.x);
Debug.Log(foodarea.bounds.max.x);
Debug.Log(foodarea.bounds.min.y);
Debug.Log(foodarea.bounds.max.y);
RandomPosition();
}
void RandomPosition()
{
transform.position = new Vector3(
Random.Range(foodarea.bounds.min.x, foodarea.bounds.max.x),
Random.Range(foodarea.bounds.min.y, foodarea.bounds.max.y),
0);
}
}
這樣蘋果被貪吃蛇吃掉以後還會在場景範圍內生成了!