Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

c# - 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. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Vector3.Dot() for that. 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 (e.x., direction from head to food).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...