简体   繁体   English

无法限制对象的旋转 Unity3D

[英]Can't limit Object's Rotation Unity3D

I have an object in my scene that move forward and rotate with input.GetAxis, and I want to limit its X rotation between -45 and 45 degree.我的场景中有一个对象向前移动并随 input.GetAxis 旋转,我想将其 X 旋转限制在 -45 到 45 度之间。 So I tried the Clamp method but the object can't rotate anymore!所以我尝试了 Clamp 方法,但对象不能再旋转了! is there something wrong in my code?我的代码有问题吗?

float Speed = 10f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    transform.Rotate(-Input.GetAxis("Vertical") * 2f, 0, -Input.GetAxis("Horizontal"));

    float rotationX = Mathf.Clamp(transform.rotation.x, -45.0f, 45.0f);
    transform.localEulerAngles = new Vector3(rotationX, transform.localEulerAngles.y, transform.localEulerAngles.z);
}

private void FixedUpdate()
{
    transform.position += transform.forward * Speed * Time.fixedDeltaTime;
}

就我个人而言,我不会尝试直接设置 localEulerAngles,我会将旋转重置为 Quaternion.Identity(无旋转)或另一个参考变换的旋转,然后在旋转更改时围绕所需轴使用 Transform.rotate rotationX 度

The main issue your having atm is transform.rotation is a Quaternion and not a vector3.您拥有 atm 的主要问题是 transform.rotation 是四元数而不是 vector3。 Since Quaternions have a min/max value of -1/1 the vector3 X rotation can't ever be outside that range.由于四元数的最小值/最大值为 -1/1,因此 vector3 X 旋转永远不会超出该范围。

You probably wanted to do: float rotationX = Mathf.Clamp(transform.localEulerAngles.x, -45.0f, 45.0f);您可能想要这样做: float rotationX = Mathf.Clamp(transform.localEulerAngles.x, -45.0f, 45.0f);

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

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