如何在 C# (Unity) 中设置对象的最大旋转

问题描述

我试图让一艘太空船在向上行进时向上倾斜,或者在它坠落时向下倾斜,但我被卡住了,这是我目前所拥有的

 if (Input.GetKey(KeyCode.Space)) //If spacebar pressed
        {
            playerRb.AddForce(Vector3.up * floatForce,ForceMode.Impulse); // Add force upwards to player
        }

        // Rotates upwards
        if (Input.GetKey(KeyCode.Space))
        {
            if (transform.rotation.x != -maxRotation)
            {
                transform.Rotate(-rotationSpeed,0f,0f * Time.deltaTime);
                transform.Rotate(-maxRotation,0f);
            }
        }

当我按下空格键时它会无限旋转......

有什么帮助吗? 谢谢

解决方法

如果要限制对象的旋转,可以修改 eulerAngles 属性值。

示例

以下脚本采用几个向量,并确保对象旋转保持在它们的 x、y、z 值之间的范围内。

using UnityEngine;

public class RotationLimitter : MonoBehaviour
{
    [SerializeField]
    private bool runOnUpdate = true;
    [SerializeField]
    private bool runOnLateUpdate = false;
    [SerializeField]
    private bool runOnFixedUpdate = false;
    
    [Space]
    [SerializeField]
    private Vector3 minRotation = Vector3.zero;
    [SerializeField]
    private Vector3 maxRotation = Vector3.zero;

    private void Update()
    {
        if (runOnUpdate)
            LimitRotation();
    }

    private void LateUpdate()
    {
        if (runOnLateUpdate)
            LimitRotation();
    }

    private void FixedUpdate()
    {
        if (runOnFixedUpdate)
            LimitRotation();
    }

    private void LimitRotation()
    {
        float x = Mathf.Clamp(transform.eulerAngles.x,minRotation.x,maxRotation.x);
        float y = Mathf.Clamp(transform.eulerAngles.y,minRotation.y,maxRotation.y);
        float z = Mathf.Clamp(transform.eulerAngles.z,minRotation.z,maxRotation.z);

        transform.eulerAngles = new Vector3(x,y,z);
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...