I’m creating a small 2D game and I have this enemy that needs to rotate towards the player. I want the enemy to do it at a slow speed and not constant. Now, this sounds like a common problem, but when I try to change the maxDegreesDelta I’m only getting the max degrees I can turn and not anything with speed. I have tried using code from other answers but not getting my answer.
Quaternion.Slerp
allows you to interpolate between two rotation values. The third parameter of this function is a percentage value - basically, how far along the way between “Rotation A” and “Rotation B” you want the returned rotation to be. If you use Quaternion.Slerp(a, b, 0.0f)
, the returned rotation will be equal to “Rotation A”, if you use Quaternion.Slerp(a, b, 1.0f)
it will be equal to “Rotation B”, and if you use Quaternion.Slerp(a, b, 0.5f)
if will be a halfway rotation between A and B. This function is great for interpolating between two known rotations - it can work to get a specific point between those two rotations, or it can be used to iterate between them step by step, but you have to, at all times, know your starting rotation and your ending rotation. For your purpose Quaternion.RotateTowards
will be a better choice, since you’ll have ever changing values of rotation that you want to happen with the same speed (not during the same amount of time).
Quaternion.RotateTowards
moves the passed “Rotation A” a single step towards “Rotation B”. That step is the third parameter of the function (provided in degrees). The “step” is actually the maximum rotation a single step will move - RotateTowards
moves your rotation towards your target until it is reached, but it won’t move past it.
You can easily use it to change your object’s rotation - try putting this code in your Update
method:
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 15.0f * Time.deltaTime);
Every frame your Update
method will run this function, and it will move your transform.rotation
towards targetRotation
with the rotation speed of 15 degrees a second. Try it out on a new object - create a new object with a Sprite
, set its starting rotation to 0,0,0 and add a script that in the Update
method does the rotation:
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0.0f, 0.0f, 180.0f), 15.0f * Time.deltaTime);