0
votes

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.

2
Maybe change the value of viewRange.MrFox
Isn't looking up/down a rotation on the x axis?ssb
I would create a debug window and display the value of rotationY. Find the max and min value that you desire and use some if statements to limit the value of rotationY to your desired range. I dont really know unity or I would have a better answer. This is how I did it in XNA.Linuxx

2 Answers

1
votes

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

1
votes

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