Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Slowly rotate toward an object

Discussion in 'Physics' started by Eliecompteperso, Oct 28, 2019.

  1. Eliecompteperso

    Eliecompteperso

    Joined:
    Oct 9, 2019
    Posts:
    1
    Hi i am trying to make a missile point a at target when it get at a certain distance from it. I managed to point the missile with transform.LookAt() but it turns instantly. Is there any alternative to make it follow the target in a more natural way.

    thanks in advance
     
    Last edited: Oct 28, 2019
  2. Ukounu

    Ukounu

    Joined:
    Nov 2, 2019
    Posts:
    9
    You can use Lerp to gradually rotate an object towards target.

    Code (CSharp):
    1. public Transform target;
    2. public float speed = 0.1f;
    3.  
    4. void Update()
    5. {
    6.  Vector3 relativePos = target.position - transform.position;
    7.  Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
    8.  transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.time * speed);
    9. }