Add camera constraints?

As a default. the camera has a rotation of zero. I want to put a limit on it, so you can only rotate 45 degrees in either direction (so, from 0-45 or 0-315).

How would I word a check like that? I know it will be something like:

if(transform.eulerAngles > 45f)
{
transform.eulerAngles = 45f;
}

if(transform.eulerAngles <315f)
{
transform.eulerAngles = 315f;
}

But that doesn’t work mathematically. What am I missing?

The first problem is that transform.euilerAngles returns a Vector3…

First of all, if you’re using a Cinemachine camera, you can restrict the camera’s rotation in the camera’s settings, look for axis control and restrict the x settings to -45, 45.

If you’re trying to do it this way, you’re going to have to do some extra maths…

This is off the top of my head, but it should be close (better to use Cinemachine settings!)

float rotation = transform.eulerAngles.y;
if(rotation > 180f) rotation -=360;  //Normalize to + or - from zero
rotation = Mathf.Clamp(rotation, -45f, 45f);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, rotation, transform.eulerAngles.z);
1 Like

Privacy & Terms