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?