user6100409
user6100409

Reputation:

Limit camera rotation angle

I want to able to restrict camera rotation after a certain point and only be able to rotate in a certain area, this is the code so far...

void Update() {
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    desiredy = Camera.main.transform.eulerAngles.y;
    desiredx = Camera.main.transform.eulerAngles.x;

    if (!(desiredy < maxy && desiredy > miny))
    {
        //i dont know what to put in here, i have tried everything
    }


    else if (!(desiredx < maxx && desiredx > minx))
    {
         //i dont know what to put in here, i have tried everything
    }

    else
    {
        localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
        transform.rotation = localRotation;
    }
}

Upvotes: 4

Views: 1018

Answers (1)

Programmer
Programmer

Reputation: 125455

You are making this complicated with your unnecessary logic. All you need is the Mathf.Clamp function that makes sure that your value is within specified range.

void Update()
{
    rotateCamera();
}


public float xSensitivity = 100.0f;
public float ySensitivity = 100.0f;

public float yMinLimit = -45.0f;
public float yMaxLimit = 45.0f;

public float xMinLimit = -360.0f;
public float xMaxLimit = 360.0f;

float yRot = 0.0f;
float xRot = 0.0f;

void rotateCamera()
{
    xRot += Input.GetAxis("Mouse X") * xSensitivity * Time.deltaTime;
    yRot += Input.GetAxis("Mouse Y") * ySensitivity * Time.deltaTime;
    yRot = Mathf.Clamp(yRot, yMinLimit, yMaxLimit);
    Camera.main.transform.localEulerAngles = new Vector3(-yRot, xRot, 0);

}

Upvotes: 4

Related Questions