【问题标题】:manually change a rotation in unity手动统一更改旋转
【发布时间】:2021-05-29 14:28:22
【问题描述】:

所以这是我的问题:我在 Unity 中有一个对象,即我的 Player。 我希望这个玩家能够面对他移动的方向。 但我不知道如何旋转对象,直到释放特定键然后将旋转重新定位到 0,0,0

我试过这个代码

public class PlayerAction : MonoBehaviour
{
public float horizontalInput;
public float verticalInput;
// Start is called before the first frame update
void Start()

    
}

// Update is called once per frame
void Update()
  {
    horizontalInput = Input.GetAxis("Horizontal");
    verticalInput = Input.GetAxis("Vertical");

    if (horizontalInput > 0)
    {
        transform.Rotate(0, 90, 0);
    }
  }
}

我在看四元数,但在任何论坛上什么都不懂。

为了澄清我想手动更改播放器的旋转

【问题讨论】:

    标签: unity3d input rotation transform quaternions


    【解决方案1】:

    找到这个示例,您可以在其中围绕 y 轴旋转到每一边并分别重置回原始旋转。

    using UnityEngine;
    
    public class Rotation : MonoBehaviour {
        private Quaternion startingRot;
    
        void Start() {
            startingRot = transform.rotation;
            }
    
        void Update() {
    
            if (Input.GetKeyDown(KeyCode.P)) {
                transform.Rotate(0, 45, 0);
            }
    
            if (Input.GetKeyDown(KeyCode.O)) {
                transform.Rotate(0, -45, 0);
            }
    
            if (Input.GetKeyUp(KeyCode.L)) {
                transform.rotation = startingRot;
            }
        }
    }
    

    四元数是一种处理旋转的数学工具。它们远不如 eulerAngles 直观,但计算效率更高,并且解决了 eulerAngles 的一个已知问题,Gimbal lock

    你暂时不需要担心这个,只是为了你的信息:

    Unity 在代码中提供了与欧拉角进行交互的方式,与在编辑器中一样,但旋转是由四元数处理的。这就是为什么很多时候你会在 unity 的编辑器变换旋转窗口中发现一些意想不到的值,因为 unity 会从它内部处理的四元数永久转换为编辑器用户界面中显示的欧拉角。

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2018-09-04
      • 1970-01-01
      • 2021-05-24
      • 2010-10-16
      相关资源
      最近更新 更多