- Home /
How do I make an object rotate towards to another object with rotation speed?
I want an enemy chasing the player but I wouldn't want the enemy to be able to look at me instantaneously.
This is my code for the rotation:
Vector3 dir = player.transform.position - this.transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle - 90.0f, Vector3.forward);
*edit: Changed added -90.0f at the last line because the sprite was facing the target sidewards.
Answer by Zodiarc · Sep 09, 2014 at 02:58 PM
I've changed my code:
transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.AngleAxis(angle - 90.0f, Vector3.forward), rotationSpeed);
But it seems that the sprite is still facing me quickly regardless of the value of rotationSpeed.
Am I using Lerp right?
You also need to use Time.deltaTime. In my understanding this code should look like this:
var rotationTime: float = 0.0f;
rotationTime += rotationSpeed * Time.deltaTime;
transform.rotation = Quaternion.Lerp(fromRotation, toRotation, rotationTime);
If rotation Speed is 1, then the rotation will take 1 second (I didn't use Quaternion.Lerp till now but I'm assu$$anonymous$$g that it will work the same like $$anonymous$$athf.Lerp.
Fixed it. Used localEulerAngles and RotateTowards. I had trouble using Quaternion.Lerp
var direction = (player.transform.position - transform.position).normalized;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(direction, transform.up), rotationSpeed * Time.deltaTime* 9.0f);
transform.localEulerAngles = new Vector3(0, 0, transform.localEulerAngles.z);
Thanks for the help though.
Answer by Jan_Julius · Sep 09, 2014 at 03:32 PM
Try using Time.deltaTime
I did, I've also tried to use Quternion.Lerp in this here code:
transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.AngleAxis(angle - 90.0f, Vector3.forward), Time.deltaTime * rotationSpeed);
But it still behaves the same way as my original code.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162635im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotate while moving forward 1 Answer
Rotate object based on normalized Vector2? 1 Answer
Gradually reduce speed 1 Answer
2 fingers sprite rotation 1 Answer
Rotate an object around another object at an angle from the X axis? 1 Answer