- Home /
Unity 2d rotate to face the player at a constant speed
I've been looking on the forums and can't find quite what I need for help. What I want is for my turret to rotate so that it is facing the player, but do so at a constant speed. I also need to ensure that it only does so within a specific range so that the turret doesn't go into the ground. Everything I have seen so far doesnt fix the issue of speed. No matter what I try the turret will always rotate faster the greater the angle it needs to rotate is. I want to ensure that no matter how far it needs to rotate it will always do it at the same speed.
Answer by BLVDE · Nov 15, 2020 at 04:40 PM
Mathf.MoveTowardsAngle could help
You'll have to give it the current angle, the target angle and the maxDelta. It takes every Angle as a float. maxDelta represents the the "Jump" you can make each time its called so you can insert your Angle/second and multiply it by your fixedDeltaTime (assuming you use this in the FixedUpdateMethod).
The result is your new Angle.
Edit: when you are below the Turret you can try to make the code pretend you are at the same y-level as the turret.
Answer by Zubzuke · Nov 15, 2020 at 03:37 PM
Look for some quaternion rotation tutorials. It should work even if it's 2D as you can ignore the 3rd axis. You may have to use some intermediary Vector3 for the calculations if you're only using Vector2. You will also want to use a rotation speed along with deltaTime to keep the speed steady. Here's a quick tutorial about quaternion rotations:
Answer by link111348 · Nov 15, 2020 at 06:32 PM
What you say BLVDE seems to be closer to what I want, but how would I find what angle I need it to rotate to?
first you take the location of your target and subtract the turrets location. Let's call that targetVector. Then you use that piece of code: float rotationZ = $$anonymous$$athf.Atan2(targetVector.y, targetVector.x) * $$anonymous$$athf.Rad2Deg;
rotationZ is your targetRotation you want to "move" to (z assu$$anonymous$$g you are working from a front view).
Also when you "pretend" to be at the same height as the turret, "pretend" to be 0.01 higher on y axis since floats can be quite inaccurate and it can result in the turret turning the wrong direction.
Source for the Atan2 idea, was to lazy to think about triangles at that moment ^^: https://answers.unity.com/questions/1023987/lookat-only-on-z-axis.html
Your answer
Follow this Question
Related Questions
Enemy Rotation Problem 1 Answer
GameObject facing fowards 1 Answer
Flip the player with arm rotation 2 Answers
Getting the face direction 2 Answers
Control object yaw by two axis 1 Answer