简体   繁体   English

如何计算蛇游戏中玩家身后的游戏角度object

[英]How to calculate the angle of a game object behind the player in a game of snake

I am creating a game of Snake in the Unity Engine with a 2d Orthographic camera.我正在使用 2d 正交相机在 Unity 引擎中创建 Snake 游戏。 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这是我要实现的目标的粗略草图

Use Vector3.Dot() for that.为此使用Vector3.Dot() Remember, that it operates on directions , not positions - so you probably want to compare transform.forward of snake head with a difference of food and head position (ex, direction from head to food).请记住,它在方向上运行,而不是位置- 所以你可能想比较蛇头的transform.forward与食物和头部 position 的差异(例如,从头部到食物的方向)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM