Question

I used Unity to create a simple first-person game, where you use the WASD-keys to move around and the mouse to look around. At the moment the camera rotation on the x- and y-axis is not restricted (if you look up you can turn a complete 360° on the y-axis). Now I want to cap this, so you can not go further than looking straight up. My scrip so far (no restrictions yet):

public float rotationY = 0;
public float viewRange = 90.0;

void Update () {

    float rotationX = Input.GetAxis ("Mouse X") * mouseSensitivity;
    transform.Rotate (0, rotationX, 0);

    rotationY = Input.GetAxis ("Mouse Y") * mouseSensitivity;
    rotationY = Mathf.Clamp (rotationY, -viewRange, viewRange);
    Camera.main.transform.Rotate (-rotationY, 0, 0);
                }

Now i tried to limit the y-axis camera movement by replacing the last line by

Camera.main.transform.localRotation = Quaternion.Euler (rotationY,0,0);

But unfortunately this results in not being able to rotate the camera in y-direction at all.

Was it helpful?

Solution

You have to subtract the "Mouse Y" axis rotation on each update, so just replace this:

rotationY = Input.GetAxis ("Mouse Y") * mouseSensitivity;

...with this:

rotationY -= Input.GetAxis ("Mouse Y") * mouseSensitivity;

It's also important that you don't use Camera.main.transform.Rotate, but uses localRotation instead (as you point out yourself).

OTHER TIPS

The problem is that Transform.Rotate applies rotation (not sets the angle as you can expect). So your clamp has no effect. What you want to clamp is Transform.localEulerAngles

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top