Limit rotation for FPS controller

Hey, writing a custom FPS controller! But I can’t seem to get my camera to limit the rotation of how far you can look up and down. Here’s my code

var rotSpeed : float;
function Update()
{
	var rot : float = Input.GetAxis("Mouse Y") * rotSpeed;
	transform.Rotate(-rot, 0, 0);
}

btw, i have looked everywhere for hours. Can’t find it! Please help! Thanks

In case you haven’t found the answer yourself yet:

you can clamp the rotation between 2 values. I would do it this way:

var rotSpeed : float;
private var rotVertical : float = 0;

function Update()
{
	rotVertical += Input.GetAxis("Mouse Y") * rotSpeed;
	transform.localEulerAngles.x = Mathf.Clamp(-rotVertical, -60, 60); 
}

This should work I think :slight_smile:

Instead of using the input value directly calculate the change in input each frame.

var rotationSpeed : float;
var currentRotation : float;
var lastInput : float;

function Update()
{
    // Calculate change in input
    var  deltaInput : float = (Input.GetAxis("Mouse Y") - lastInput) * rotationSpeed;
    lastInput = Input.GetAxis("Mouse Y");

    // Apply change to current rotation to calculate new rotation
    var newRotation : float = currentRotation + deltaInput;

    // Clamp new rotation to appropriate range
    newRotation = Mathf.Clamp(newRotation, minimumRotation, maximumRotation);

    // Undo currently applied rotation
    transform.Rotate(-currentRotation, 0, 0);

    // Apply new rotation
    transform.Rotate(newRotation, 0, 0);

    // Remember currently applied rotation
    currentRotation = newRotation;
}

This should work, but if you are not applying any other rotations to the camera, it would be better to set the rotation directly. Undoing the last rotation every frame like this may accumulate floating point error so your zero may eventually drift. How much I couldn’t say.

If you have one script that applies all camera rotations, you can assign the local rotation (i.e. transform.localRotation = something) directly and can avoid this problem.

Edit: I wrote this post assuming that input returned an absolute position and that was causing your problem, but that assumption could be wrong. I actually did this exact thing with a FPS controller not too long ago, but I may have mixed up some of the details.