简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM