How to check when Quaternion Slerp is `done`

I have a top down Game, some turrets and enemies. The turrets rotate to the enemy and the enemy follows a path and rotate (follows) the generated path line.

I need to know when the turret completed the rotate so I can implement relevant code here

My scripts are:

Turrets chasing the enemies

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Vector3 enemyPosition = collision.transform.position;
            Vector3 vectorToTarget = (enemyPosition - transform.position).normalized;
            float Angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
            Quaternion q = Quaternion.AngleAxis(Angle, Vector3.forward);
            transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * RotationSpeed);
            inVision = true;
        }
    }

Enemies moving and rotating correctly to the generated path line:

   Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
   SteerTowardsTarget(direction);
   Vector2 force = direction * Speed * Time.deltaTime;
   rb.AddForce(force);

    void SteerTowardsTarget(Vector2 direction)
    {
        float targetRot = Vector2.Angle(Vector2.right, direction);
        if (direction.y < 0.0f)
            targetRot *= -1;
        float rot = Mathf.MoveTowardsAngle(transform.localEulerAngles.z, targetRot, 1.0f);
        transform.eulerAngles = new Vector3(0f, 0f, rot);
    }

Well first, you’re using Slerp incorrectly.
The third parameter should not be something that represents movement over time (I.E: Time.deltaTime * RotationSpeed), it should be a number between 0 and 1. This is the same for all other lerp-type methods.

The third parameter represents the percentage between the two rotations, where:

  • 0 = Exactly the first rotation value.
  • 1 = Exactly the second rotation value.
  • 0.5 = The half-way point between the two rotations.

With that in mind, you can tell when a Slerp is “done” by reading the value of the third parameter, checking if it’s either 0 (for the first rotation) or 1 (for the second rotation).
For example:

public class Example : MonoBehaviour {
   public float lerpSpeed;
   private float lerpPercent = 0f;

   void Update() {
      lerpPercent = Mathf.MoveTowards(lerpPercent, 1f, Time.deltaTime * lerpSpeed);

      transform.rotation = Quaternion.Slerp(/*from-rotation*/, /*to-rotation*/, lerpPercent);

      if(lerpPercent >= 1f) {
         //Rotation slerp has finished. Do something else now.
      }
   }
}
3 Likes

Solved, thank you!