Search code examples
c#unity-game-enginerotationquaternions

Unity, rotate an object in axis and back to starting point in the same direction


I want to rotate an object in the Y direction at constant speed. When stopped I want to rotate back to Quaternion.identity in the same direction.

public bool spin;
public float speed;

private void Update() {
    if (spin) {
        transform.Rotate (-Vector3.up, Time.deltaTime * speed, Space.World);
    } else if (transform.rotaion != Quaternion.identity) {
        transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.identity, Time.deltaTime * speed);
    }
}

This works great but it spins back on opposite direction. How do you force it to keep spinning on original direction to Quaternion.identity?


Solution

  • This works great but it spins back on opposite direction.

    RotateTowards will take the shortest path to its target - whichever direction that may be.

    How do you force it to keep spinning on original direction to Quaternion.identity?

    Reverse direction when rotation passes 180 degrees (or halfway):

    var dir = transform.eulerAngles.y < 180f ? 1f : -1f;
    Quaternion.RotateTowards(rotation, Quaternion.identity, Time.deltaTime * speed * dir);