I am creating a game of Snake in the Unity Engine with a 2d Orthographic camera. I want to detect if a food pellet is behind or in front of the snake at a certain point.
I have tried multiple methods such as this one but I have not been able to figure this out.
IEnumerator ChangeFood()
{
//waits three seconds then puts all active food instances into a list, then picks a random object from that list and changes it
yield return new WaitForSeconds(3f);
GameObject[] foodList = GameObject.FindGameObjectsWithTag("Food");
if (foodList.Length > 0)
{
//List<Vector2> foodsBehindSnake = new List<Vector2>();
foreach(GameObject food in foodList)
{
//If angle required to turn towards food is greater than 90, food will be considered as behind snake
float angleToFood = Mathf.Atan2(food.transform.position.y - this.transform.position.y, food.transform.position.x - this.transform.position.x) * Mathf.Rad2Deg;
Debug.Log(angleToFood);
if (angleToFood <=90f)
{
Debug.Log("FOOD AT" + food.transform.position + " IS BEHIND SNAKE");
food.GetComponent<SpriteRenderer>().color = Color.magenta;
}
}
}
yield return null;
}
here is a rough sketch of what I am trying to achieve
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…