【问题标题】:Unity3d return to original rotationunity3d返回原始旋转
【发布时间】:2016-05-07 20:38:11
【问题描述】:

我正在尝试让 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);
    }
}

但我没有运气。我怎样才能让它工作?

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    我认为,只需保存原始旋转并使用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);
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      相关资源
      最近更新 更多