c# – How to lock z rotation in Unity3D?

c# – How to lock z rotation in Unity3D?

just add a rigidbody and lock the z rotation, and turn off gravity. you can set its collider to trigger so it dosnt hit anything.

This is a solution I wrote for completely locking camera rotation without using a RigidBody. Just create this script and add it to your camera (or whatever you want to lock).

public class RotationLock : MonoBehaviour
{
    private Quaternion lockedRotation;
    
    void Start() { lockedRotation = transform.rotation; }
    void Update() { transform.rotation = lockedRotation; }
}

Heres another version that lets you choose which axes to lock. I wrote it for a 3D phone game where the user could rotate their view in place by swiping.

public class RotationLock : MonoBehaviour
{
    public bool lockX, lockY, lockZ;
    private Vector3 startRotation;

    void Start() { startRotation = transform.rotation.eulerAngles; }
    void LateUpdate()
    {
        Vector3 newRotation = transform.rotation.eulerAngles;
        transform.rotation = Quaternion.Euler(
            lockX ? startRotation.x : newRotation.x,
            lockY ? startRotation.y : newRotation.y,
            lockZ ? startRotation.z : newRotation.z
        );
    }
}

There may be more efficient solutions, but these work in a pinch and wont involve the physics system!

c# – How to lock z rotation in Unity3D?

Try adding code that will reset the tilt of the camera at the end of each frame.

var rot = transform.rotation;
Camera.main.transform.rotation = new Quaternion(rot .x,rot .y, 0, rot .w);

Leave a Reply

Your email address will not be published.