Jamshaid Alam Jamshaid Alam - 1 month ago 15
C# Question

How to clamp camera in Unity3D

My code is not working, I am trying to clamp the camera, but its not working. How to clamp the camera?

using UnityEngine;
using System.Collections;

public class MoveCamera : MonoBehaviour
{

public float sensitivity = 4.0f;
private Vector3 mouseOrigin;
private bool isRotating;

private float speed = 2.0f;

private float minX = -45.0f;
private float maxX = 45.0f;

private float minY = -10.0f;
private float maxY = 10.0f;

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

void Update ()
{
if (Input.GetMouseButtonDown (0)) {

mouseOrigin = Input.mousePosition;
isRotating = true;
}

if (!Input.GetMouseButton (0))
isRotating = false;

if (isRotating) {

Vector3 pos = Camera.main.ScreenToViewportPoint (Input.mousePosition - mouseOrigin);
transform.RotateAround (transform.position, transform.right, -pos.y * sensitivity);
transform.RotateAround (transform.position, Vector3.up, pos.x * sensitivity);

rotationY = Mathf.Clamp (rotationY, minY, maxY);
rotationX = Mathf.Clamp (rotationX, minX, maxX);
transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0);
}
}
}

Answer

OK, So I fixed it. Here is complete code.

using UnityEngine;
using System.Collections;

public class MoveCamera : MonoBehaviour 
{

    public float sensitivity = 4.0f;        
    private Vector3 mouseOrigin;
    private bool isRotating;
    public GameObject cam;

    void Start()
    {
    }

    protected float ClampAngle(float angle, float min, float max) {

        angle = NormalizeAngle(angle);
        if (angle > 180) {
            angle -= 360;
        } else if (angle < -180) {
            angle += 360;
        }

        min = NormalizeAngle(min);
        if (min > 180) {
            min -= 360;
        } else if (min < -180) {
            min += 360;
        }

        max = NormalizeAngle(max);
        if (max > 180) {
            max -= 360;
        } else if (max < -180) {
            max += 360;
        }

        return Mathf.Clamp(angle, min, max);
    }

    protected float NormalizeAngle(float angle) {
        while (angle > 360)
            angle -= 360;
        while (angle < 0)
            angle += 360;
        return angle;
    }


    void Update () 
    {

        if (Input.GetMouseButtonDown (0)) {

            mouseOrigin = Input.mousePosition;
            isRotating = true;
        }

        if (!Input.GetMouseButton (0))
            isRotating = false;

        if (isRotating) {

            cam.transform.localEulerAngles = new Vector3(0, ClampAngle(cam.transform.localEulerAngles.y, -45, 45), 0);
            Vector3 pos = Camera.main.ScreenToViewportPoint (Input.mousePosition - mouseOrigin);
            transform.RotateAround (transform.position, transform.right, -pos.y * sensitivity);
            transform.RotateAround (transform.position, Vector3.up, pos.x * sensitivity);
        }
    }
}
Comments