简体   繁体   中英

Determining which direction to rotate a character in unity?

I am currently having a lot of issues trying to determine which direction is the shortest path between two angles. I am programming a boid in Unity2D, and I am working on the separation aspect. For context, my current system works by creating a specified amount of gameobjects around the boid (I found that 16 of these work nicely). These gameobjects have their own scripts which draws a linecast to the parent boid, and records it's angle to the player. If the linecast hits a wall, or a boid, it adds the cosine and sine of it's angle to two separate lists that are stored in the parent boid. The parent boid calculates the average of these two lists and creates a vector based on that. The boid gets the angle to that vector, and adds 180 degrees to that to find the direction it needs to head in in order to not hit the object. As horrifically inefficient it may sound, it was the only way I could think to do this, and works well.

Now, what doesn't work is rotating the boid towards that goal direction. I do not want the boid to instantly lock into position, but to slowly rotate. I want this because it adds a lot of variation to the boid's movement. The movement takes the current direction that the boid is facing and moves that way. For the most part, I got this to work with this code:

void Rotate()
    {
        if (currentRotation != goalRotation)
        {
            int sign = (currentRotation < goalRotation) ? 1 : -1;
            rotateSpeed = Mathf.Abs(currentRotation - goalRotation) / 10;
            currentRotation += rotateSpeed * sign;
            if (Mathf.Abs(currentRotation - goalRotation) <= .5) //If the current rotation is close, just make it the goal rotation.
            {
                currentRotation = goalRotation;
            }
        }
    }

(Angles are based off the unit circle)

I really like how this starts the boid rotating fast, and slows down as the boid reaches the desired angle. So, this code works, except when the current rotation is something like 350 degrees, and the goal direction is something like 10 degrees. The boid will rotate clockwise, even though the shortest path is counterclockwise. I know exactly why, but have no clue how to fix it. Any help would be appreciated.

I don't understand what boid is, but here's the solution:

Not smooth

transform.LookAt(target);

Smooth

var targetRotation = Quaternion.LookRotation(targetObj.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);

You can combine Quaternion.RotateTowards and Quaternion.Slerp to achieve ultra smooth solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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