Unity3d return 到原始旋转

Unity3d return to original rotation

我正在尝试让 3D 对象在玩家松开任何影响键时缓慢 return 到其原始旋转。

这是我目前拥有的:

using UnityEngine;
using System.Collections;

public class ShipController : MonoBehaviour {

    public float turnRate;
    public Transform baseOrientation;

    private Vector3 worldAxis, worldAxisRelative;
    private Rigidbody rb;

    void Start () {
        rb = GetComponent<Rigidbody> ();
        worldAxis = new Vector3 (0, 0, 0);
        worldAxisRelative = transform.TransformDirection (worldAxis);
    }

    void Update () {

    }

    void FixedUpdate()
    {
        if (Input.GetKey (KeyCode.LeftArrow)) {
            rb.transform.Rotate (Vector3.down * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.RightArrow)) {
            rb.transform.Rotate (Vector3.up * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.UpArrow)) {
            rb.transform.Rotate (Vector3.left * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.DownArrow)) {
            rb.transform.Rotate (Vector3.right * turnRate * Time.deltaTime);
        }
        axisAlignRot = Quaternion.FromToRotation (worldAxisRelative, worldAxis) ;
        rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, axisAlignRot * transform.rotation, 1.0f * Time.deltaTime);
    }
}

但我运气不好。我怎样才能让它工作?

我认为,只需保存原始旋转并使用 Quaternion.RotateTowards,这应该相对容易完成。您根本不需要为此使用刚体。

using UnityEngine;
using System.Collections;

public class ShipController : MonoBehaviour {

    public Quaternion originalRotation;

    void Start () {
        originalRotation = transform.rotation;
    }

    void Update()
    {
        if (Input.GetKey (KeyCode.LeftArrow)) {
            transform.Rotate (Vector3.down * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.RightArrow)) {
            transform.Rotate (Vector3.up * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.UpArrow)) {
            transform.Rotate (Vector3.left * turnRate * Time.deltaTime);
        }
        if (Input.GetKey (KeyCode.DownArrow)) {
            transform.Rotate (Vector3.right * turnRate * Time.deltaTime);
        }
        transform.rotation = Quaternion.RotateTowards(transform.rotation, originalRotation, 1.0f * Time.deltaTime);
    }
}

这应该有效。您可能需要稍微改变一下条件,因为如果您实际上按下四个键中的任何一个,目前您也会转向原始旋转。