简体   繁体   English

如何在Unity中锁定相机的Z轴旋转?

[英]How can I lock my camera Z axis rotation in Unity?

I am using my mouse position to rotate my camera: 我使用鼠标位置旋转相机:

void FixedUpdate()
{
    transform.Rotate(-Input.GetAxis("Mouse Y") * rotationspeed * Time.deltaTime, Input.GetAxis("Mouse X") * rotationspeed * Time.deltaTime, 0);
}

The problem is that after rotating it for a time the camera starts rotating on the Z axis as well. 问题在于,旋转一段时间后,相机也会开始在Z轴上旋转。 What should I do to lock the Z axis rotation of the camera? 如何锁定相机的Z轴旋转?

If you want to rotate a object in two axis the third axis will rotate by default, you can not lock this because its the fact of real world . 如果要沿两个轴旋转对象,则默认情况下,第三个轴将旋转,因为它是真实世界,所以无法锁定它。 Try this in real world 3d object rotate any two axis third will rotate automatically.If you rotate one axis other two will be fixed . 在现实世界中尝试此操作3d对象旋转的任何两个轴都会自动旋转。如果旋转一个轴,则另外两个将固定。 Thanks. 谢谢。

Transform.Rotate has an optional parameter Transform.Rotate具有可选参数

Space relativeTo = Space.Self

so by default it is set to Sapce.Self so it rotates around the local axes of the object. 因此默认情况下将其设置为Sapce.Self以使其绕对象的局部轴旋转。

So what happens is once you look down changing the local X-axis your local Y-axis doesn't point straight up anymore but is rather pointing a bit forward now. 所以发生的事情是,一旦您向下看更改本地X轴,您的本地Y轴不再指向正上方,而是现在指向前方。 So if you now rotate around that local Y-axis your local horizont is suddendly not aligned with the world's horizont anymore. 因此,如果您现在绕着该局部Y轴旋转,则您的局部视界突然不再与世界的视界对齐。


What you want to do instead (you can actually see it also in the example in the link above) is rotating around the Y-axis in world space but rotate around X-axis in local space 相反,您想要做的事情(实际上您也可以在上面的链接的示例中看到) 在世界空间中绕着Y轴旋转,而在局部空间中绕着X轴旋转。

like this 像这样

[SerializeField] private float rotationspeed;

private void FixedUpdate()
{
    // rotate around global world Y
    transform.Rotate(Input.GetAxis("Mouse X") * rotationspeed * Time.deltaTime, 0, 0, Space.World);

    // rotate around local X
    transform.Rotate(0, -Input.GetAxis("Mouse Y") * rotationspeed * Time.deltaTime, 0);
}

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

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