Clamping objects localrotation not working (C#)

I don’t know why i’m having such a hard time with this it’s a basic script. Basically I have a camera that i need to be able to orbit another object but only to an extent on the x axis it can circle it on y as much as it wants for all i care. But the x needs to stay between two values which I assigned via floats and tried restricting via Mathf.Clamp however the Vector3 does stay within the boundaries of the clamp when i apply it to the rotation it’s as if it doesn’t apply.

This is a child of an object i’m working with so I must use localRotation instead of rotation

Here is the script and to be more precise it’s line 26 where it should update the objects localrotation but is not.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
	public Transform target;
	public Camera camera;

	public float minX;
	public float maxX;

	void Update()
		//Allow Horizontal and Vertical Rotation to be controlled by the mouse
		camera.transform.RotateAround (target.position, target.up, Input.GetAxis ("mouse_axis_0"));
		camera.transform.RotateAround (target.position, target.right, Input.GetAxis ("mouse_axis_1"));

		//Store the current rotation in euler angles
		Vector3 localAngles = camera.transform.localEulerAngles;

		//Make sure the the player cannot move the mouse to far horizotnally and vertically
		localAngles.x =  Mathf.Clamp (camera.transform.localRotation.eulerAngles.x, minX, maxX);
		localAngles.z = 0f;

		//Apply the rotation
		camera.transform.localRotation = Quaternion.Euler (localAngles);

		//Make sure the camera is looking at crash
		camera.transform.LookAt (target);

the very last line of your update function tells the camera to lookat the target, everything youre doing before this is pretty much ignored because of that, you probably want to “lookat” before you do min/max checks.

My answer consists of 2 parts:

1) The script should work fine even though odd choices are made, I assume you did input degrees for the min and max values even though unity uses radians.

2) You may consider to cleanly calculate the new position, then clamp it, then transform it. That way you could easily extract code parts and reuse or replace them. It makes it also easier to read when you come back later. And believe me, you will come back later. And - assuming this script grows even a little bit - you’ll be like: wtf is going on here.

Hope 1) helps :slight_smile: