How to make an object rotate to a direction over time

Hi, I am trying to create a top down rts style controller where the player clicks somewhere on the map and a game object will rotate over time to face point where the user clicked before moving towards it. I have the movement issue down but I can’t seem to get the object to rotate properly.

The rotation code I have looks like this.

private void FixedUpdate()
{
    Vector3 dir = (_activeCommand - _rigidBody.position).normalized;

    if (dir != Vector3.zero && _isTurning)
    {
        Quaternion targetQuat = Quaternion.LookRotation(dir);
        _rigidBody.transform.rotation = Quaternion.RotateTowards(_rigidBody.transform.rotation, targetQuat, playerTurnSpeed * Time.fixedDeltaTime);
        _rigidBody.transform.rotation = Quaternion.Euler(0, 0, _rigidBody.transform.eulerAngles.z);

        if (Mathf.Abs(_rigidBody.transform.eulerAngles.z - _targetAngle) < 0.5f)
        {
            _rigidBody.transform.rotation = Quaternion.Euler(0, 0, _targetAngle);
            _isTurning = false;
        }
    }
}

For certain movements it will rotate to the correct direction as intended, in other cases it will rortate to be exactly 180 degrees the wrong way. I assume this is going to be how I handle euler angles, but not sure where I am going wrong.

Anyone know what’s going wrong?

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

Obviously you would use Mathf.MoveTowardsAngle() as noted in the above link.

1 Like

Took a little bit of tweaking on my end, but that works perfectly. Thanks

1 Like