繁体   English   中英

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

[英]How to set a max rotation on an object in 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, 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);
    }
}

暂无
暂无

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

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