繁体   English   中英

Unity3d返回原始旋转

[英]Unity3d return to original rotation

我试图让3D对象在播放器放开任何有影响力的键时慢慢恢复其原始旋转。

这是我到目前为止的内容:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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