Clamping camera rotation
I have this bit of code here, huge thanks to Holistic3D, to control camera rotation for looking around.
void Update () {
Vector2 md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y"));
md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
Quaternion rotate = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
//My addition
if (rotate.x > 0) {
rotate.x = Mathf.Clamp (rotate.x, 270f, 360f);
} else {
rotate.x = Mathf.Clamp (rotate.x, 0f, 90f);
}//if & else
//End my addition
transform.localRotation = rotate;//Rotates the camera up & down
character.transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);//Rotates the player & camera, left & right
}//Void Update
The only problem I have with it is that it doesn't clamp the cameras X rotation. And trying to clamp rotation is extremely weird. And when I try to clamp the rotation it clamps it to only 270 degrees, or 90 degrees.
Answer by AlienNova · Apr 26, 2016 at 06:51 PM
I found the answer myself. I'm still new to Unity so I didn't realize you could simply use a negative float in rotation for clamping! Final code if anyone is interested!
void Update () {
Vector2 md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y"));
md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
transform.localRotation = Quaternion.AngleAxis (-Mathf.Clamp(mouseLook.y, -90, 90), Vector3.right);//Rotates the camera up & down
character.transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);//Rotates the player & camera, left & right
}//Void Update
Hi AlienNova!
Your code is so great but im working in mobile device how can i set it in button mode?I'm using event trigger. when the button is down and tap the screen the camera goes move. how can i set the camera to zero when the button is down? please help me i i'm new to unity and coding ! :)
Your answer
Follow this Question
Related Questions
Rotation before 0 and after 360 0 Answers
Swapping Right handed Quaternions to left handed from streaming data. 1 Answer
Clamp a rotation in unity 0 Answers
Object don't rotate correctly 1 Answer