- Home /
Why is my GameObject rotation snapping to a certain angle when he reaches its destination?
I'm trying to make my NCP to rotate and look at the direction he's heading. That's not a problem. Problems is when he reaches its destination the GO rotates snapping to 90, 180, 270, etc degrees. Can't figure why he's doing that... I want the NCP to keep looking at the direction he was looking just before he stops moving, any ideas?
void Update () {
dir = transform.position - prevLoc;
float heading = Mathf.Atan2(dir.x, -dir.y);
transform.rotation = Quaternion.Euler(0f, 0f, heading * Mathf.Rad2Deg + 90);
prevLoc = transform.position;
}
A more visual example: Animated GIF
Could you add a detail regarding how your character moves from one location to the next?
If I were to guess, your character's reaching the destination and the "next direction to move" is Vector3.zero, so Atan2() is getting stuck dealing with zeroes and the resulting rotation is being thrown arbitrary values.
However, a guess is a guess and is fairly irresponsible.
So, why did I guess? If I'm wrong about how it works, then it's a demonstration of why more information is necessary to deter$$anonymous$$e what the problem is.
With that in $$anonymous$$d, if you can provide some of your code regarding movement, then it would be easier to tell whether the character's facing based on that movement is doing something expected or unusual.
Hello Eno, Thank you for your answer. Since I'm a noob with code I'm using Behavior Designer and PolyNav2D packages to create my AI
The NPC is moving with a combination of those packages, I assume is actually PolyNav who is doing the movement in the "Seek" State.
Taking a look at the package code I presume the actions happens here:
//move the agent
position += velocity * Time.deltaTime;
In any case the movement is occurring without a Rigidbody I'm sorry that I can't give more information about how the movement is happening
Answer by Kazuva · Apr 14, 2016 at 06:34 AM
it's because when it stops
dir = transform.position - prevLoc = Vector3(0,0,0);
so you need to check if it's stopped
\/ like this \/
void Update () {
if (transform.position != prevLoc) {
dir = transform.position - prevLoc;
float heading = Mathf.Atan2 (dir.x, dir.y * -1);
transform.rotation = Quaternion.Euler (0f, 0f, heading * Mathf.Rad2Deg + 90);
prevLoc = transform.position;
}
}