简体   繁体   中英

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. What should I do to lock the Z axis rotation of the camera?

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 . Thanks.

Transform.Rotate has an optional parameter

Space relativeTo = Space.Self

so by default it is set to Sapce.Self so it rotates around the local axes of the object.

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. So if you now rotate around that local Y-axis your local horizont is suddendly not aligned with the world's horizont anymore.


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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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