Quaternion.RotateTowards turning the wrong way
I'm writing a script to make an object follow a sequence of points. It turns towards the next point and then moves toward it until it gets there. Then it repeats for the next point.
Sometimes, however, it turns the wrong way, Quaternion.RotateTowards rotates more than 180 degrees to turn towards the new target. Here's the core of the code. Points is a list of Vector3.
void Update() { // See if we are pointing toward the target point. Vector3 targetPoint = Points[_currentPoint]; Vector3 targetDirection = targetPoint - transform.position; Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
float angle = Quaternion.Angle(transform.rotation, targetRotation);
if (Mathf.Abs(angle) > 0.01f)
{
// Rotate toward the target.
transform.rotation = Quaternion.RotateTowards(
transform.rotation, targetRotation,
rotationSpeed * Time.deltaTime);
}
else if (targetDirection.magnitude > 0.01f)
{
// Move toward the target.
transform.position = Vector3.MoveTowards(
transform.position, targetPoint, moveSpeed * Time.deltaTime);
}
else
{
// We are at the target. Go to the next one.
_currentPoint = (_currentPoint + 1) % Points.Count;
}
}
Any thoughts on why Quaternion.RotateTowards would sometimes not use the shortest rotation?
Answer by AfroDieter · Feb 19, 2018 at 02:38 PM
I am trying to figure the solution to this one out myself right now. I think I know however why it is sometimes rotation the wrong way: If you want to rotate to Vector3.zero (looking to the right side from above) and you looked to Vector3(0,90,0) before it is all fine. However if you looked to Vector3(0,-90,0) before it will not have it stored that way many times. instead it will say you were looking to Vector3(0,270,0) hence rotating you 270 degrees in the wrong direction instead of 90 in the correct direction.
Answer by U92 · Aug 20, 2020 at 09:26 AM
2020 still a problem any one find a solution
Vector3[] blockRotation = new[] {
new Vector3(90, 0, 0),
new Vector3(90, 30, 0),
new Vector3(90, 60, 0),
new Vector3(90, 90, 0),
new Vector3(90, 120, 0),
new Vector3(90, 150, 0),
new Vector3(90, 180, 0),
new Vector3(90, 210, 0),
new Vector3(90, 240, 0),
new Vector3(90, 270, 0),
new Vector3(90, 300, 0),
new Vector3(90, 330, 0)
};
90 and 270 break, been stuck on this for 6+ hours ZERO SOLUTIONS
Your answer
![](https://koobas.hobune.stream/wayback/20220612132843im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object rotate and slowly stop to toward 1 Answer
Rotate y-axis of child object following a rigidbody sphere parent 0 Answers
Why does RotateTowards rotate in an "orbit" rather than on the spot? Help me understand! 0 Answers
Get object's rotation around axis defined by vector 2 Answers
Why is this multiplication of two quaternion rotations not working correctly 2 Answers