Hello Guest

Author Topic: Rotate slowly to target?  (Read 4972 times)

GameDragon

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 11
    • View Profile
Rotate slowly to target?
« 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?

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Rotate slowly to target?
« Reply #1 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.

GameDragon

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 11
    • View Profile
Re: Rotate slowly to target?
« Reply #2 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.

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Rotate slowly to target?
« Reply #3 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.

GameDragon

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 11
    • View Profile
Re: Rotate slowly to target?
« Reply #4 on: November 09, 2013, 07:27:05 pm »
That makes so much more sense. Thank you very much.