- Home /
Bizzare problem with limiting camera veritcal rotation
My game is a first person shooter, where a camera is a child of my player object. Horizontal rotation is applied to the player object, vertical rotation is applied to the camera.
This is what handles cam rotation:
float x_rotation = Input.GetAxisRaw("Mouse Y");
Vector3 cam_rotation_updown = new Vector3(x_rotation, 0f, 0f) * look_sensitivity;
cam.transform.Rotate(-cam_rotation_updown);
float x = cam.transform.localEulerAngles.x;
if (x > 60 && x < 300)
{
if (x > 60 && x < 180)
{
cam.transform.localEulerAngles = new Vector3(60, 0, 0);
}
else if (x < 300 && x > 180)
{
cam.transform.localEulerAngles = new Vector3(300, 0, 0);
}
}
But the problem is if I move my mouse fast enough it'll break from the limitation of rotation that those if statements create. Then my camera ends up backwards and strangely enough its rotation isn't somewhere around 180 degrees, but around 0, which technically checks out as the correct range, but in reality it's not.
EDIT: I've noticed that when the teleport happens, y and z rotation changes from 0 to 180 instantly.
I attach this picture to clear things up:
Answer by Double-V · Apr 04, 2017 at 12:10 PM
Allright, I think I've fixed it:
float x_rotation = Input.GetAxisRaw("Mouse Y");
Vector3 cam_rotation_updown = new Vector3(x_rotation, 0f, 0f) * look_sensitivity;
cam.transform.Rotate(-cam_rotation_updown);
float x = cam.transform.localEulerAngles.x;
float y = cam.transform.localEulerAngles.y;
float z = cam.transform.localEulerAngles.z;
if (x > 60 && x < 300)
{
if (x > 60 && x < 100)
{
cam.transform.localEulerAngles = new Vector3(60, 0, 0);
if (y == 180 && z == 180)
{
cam.transform.localEulerAngles = new Vector3(60, 0, 0);
}
}
else if (x < 300 && x > 260)
{
cam.transform.localEulerAngles = new Vector3(300, 0, 0);
if (y == 180 && z == 180)
{
cam.transform.localEulerAngles = new Vector3(300, 0, 0);
}
}
}
if (y == 180 && z == 180)
{
if (x > 0 && x < 60)
{
cam.transform.localEulerAngles = new Vector3(60, 0, 0);
}
else if (x < 360 && x > 300)
{
cam.transform.localEulerAngles = new Vector3(300, 0, 0);
}
}
Since the y and z rotation was changing to 180 I just added a bunch of checks for this. If you want to have a wider view just change the values, eg. if you want to look 70 degrees up and down change all the sixties to 70 and all the three hundreds to 290. Leave the 0-s and 180-s alone.
Answer by VeeooshL · Apr 04, 2017 at 11:38 AM
You could clamp the values if they are over the specified amount. Example:
if(angle > 5){
angle = 5
}
EDIT: could also use this - https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
Your answer
Follow this Question
Related Questions
Edited mouselook script rotation clamp not working 0 Answers
Limit Rotation of physics object in 2D 1 Answer
Clamped rotation of turret problem 0 Answers
How to restrict rotation properly 2 Answers