Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Slowly rotate toward an object

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

  1. Eliecompteperso

    Eliecompteperso

    Joined:
    Oct 9, 2019
    Posts:
    7
    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
    theDrake likes this.
  2. Ukounu

    Ukounu

    Joined:
    Nov 2, 2019
    Posts:
    209
    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. }
     
    theDrake likes this.