- Home /
Rotate towards target position (mouse) at a limited speed
Hello there,
I am having trouble getting my object to rotate the way I want.
In a 2D space, I want an object to rotate towards the target position, which is the mouse position, at a limited speed. The rotation speed is based on the movement speed and the maneuverability score of the object.
This code almost works:
Vector3 vectorToTarget = targetPosition - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, rotationSpeed * Time.deltaTime);
Now I know why it's not working, but I don't know how to solve it.
The problem is that the target position changes as the object moves, which means that the interpolation points keep getting updated. The result is that the rotation slows down as the rotation distance gets smaller. I want the rotation to speed up and rotate at that speed until it reaches the target rotation.
How can this be achieved?
Answer by FlaSh-G · Aug 05, 2017 at 09:39 AM
Stay away from Quaternion.Slerp unless you read a bit about what it actually does :) . It's a common misconception to think that the "S" in Slerp stands for "smooth" or something.
Either way, if you want a constant speed, use Quaternion.RotateTowards. It does exactly what you want, which would be: Rotate from rotation A towards rotation B, but never exceed C degrees while doing so.