问题描述
我正在使用 2d Orthographic 相机在 Unity 引擎中创建 Snake 游戏。我想在某个点检测食物颗粒是在蛇的后面还是前面。
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
解决方法
为此使用 Vector3.Dot()。请记住,它作用于方向,而不是位置 - 所以您可能想将蛇头的 transform.forward
与食物和头部位置的差异进行比较(例如,从头部到食物的方向)。