2D Toolkit Forum

2D Toolkit => Support => Topic started by: GameDragon on November 09, 2013, 02:48:54 am

Title: Rotate slowly to target?
Post by: GameDragon on November 09, 2013, 02:48:54 am
I've searched and used this code to rotate my object to a target:
Code: [Select]
Vector3 direction = targetPoint - transform.position;
transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);

But I'd like to add some rotation speed to this to make it rotate more slowly. How would I go about doing this?
Title: Re: Rotate slowly to target?
Post by: unikronsoftware on November 09, 2013, 09:49:13 am
Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg gives you the angle - what you could to is start from the current transform.eulerAngles.z and then slowly move towards this instead of setting it directly.
Title: Re: Rotate slowly to target?
Post by: GameDragon on November 09, 2013, 05:22:26 pm
I've tried:
Code: [Select]
Vector3 direction = player.transform.position - transform.position;
direction = new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, direction, speed * Time.deltaTime);

But all that does it make it spin out uncontrollably.
Title: Re: Rotate slowly to target?
Post by: unikronsoftware on November 09, 2013, 07:10:31 pm
Use Math.MoveTowardsAngle to move move the rotation value from the previous value to current. You don't need to lerp all of eulerAngles, just use MoveTowardsAngle on the z value. Check the unity docs for more details.
Title: Re: Rotate slowly to target?
Post by: GameDragon on November 09, 2013, 07:27:05 pm
That makes so much more sense. Thank you very much.