How to clamp camera rotation in unity?

In this post, We will see how to clamp camera rotation in unity. Most of the unity developers face issues while clamping their cameras in unity, So here is the simple code for this issue.

clamp camera rotation in unity


How to clamp camera rotation in unity?

Clamps the given value between the given minimum float and maximum float values. Returns the given value if it is within the min and max range.

Returns the min value if the given float value is less than the min. Returns the max value if the given value is greater than the max value. Use Clamp to restrict a value to a range that is defined by the min and max values.

Basically what we do is, set the minimum and maximum rotation values before setting up actual Euler angles. Don’t forget to assign a new instance in the rotation when you do clamping with camera rotation.

Rotate camera C# script with clamping

using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public float speedV = 2.0f;
    public float speedH = 2.0f;

    private float rotationX = 0.0f;
    private float rotationY = 0.0f;

    private float minValue = -30f;
    private float maxValue = 30f;

    // Update is called once per frame
    void Update()
    {
        rotationY += speedV * Input.GetAxis("Mouse X");
        rotationX -= speedH * Input.GetAxis("Mouse Y");

        rotationX = Mathf.Clamp(rotationX, minValue, maxValue);

        transform.eulerAngles = new Vector3(rotationX, rotationY, 0);
    }
}

So basically this is how to clamp camera rotation in unity. For clamping camera rotation in android check this article.

You can also watch my video on youtube on clamp camera rotation in unity, And also check out my youtube channel, and do consider subscribing if you like the videos.


If you have any other issue or related one please drop me in the comments section below.

1 thought on “How to clamp camera rotation in unity?”

Leave a Comment

Your email address will not be published.