Euler angles clamping issue
I'm trying to clamp my player rotation to limitate it's view range. For 'y' axis it rotates the player, and for 'x' axis it rotates the camera. I already have a method that clamp angles but my problem cames when I try to clamp 'y' axis dynamically. Let me explain it. First here is the method:
float ClampAngle(float angle, float min, float max)
{
if (angle < 0f) { angle = 360 + angle; }
if (angle > 180f) { return Mathf.Max(angle, 360 + min); }
return Mathf.Min(angle, max);
}
and how I implement that for the camera rotation:
camRot = myCam.transform.eulerAngles + new Vector3(-v, 0, 0);
camRot.x = ClampAngle(camRot.x, -maxCameraRot, maxCameraRot);
myCam.transform.eulerAngles = camRot;
It works fine and it clamps rotation from -90 to 90. But now I want to clamp player rotation too when press a button. Problem here is that player rotation vary when you move, so it's not that easy like clamp between -90 and 90.
I need to store actual rotation first, then substract 90 for the minimum and add 90 for the maximum. Something like this:
pjRot = transform.eulerAngles + new Vector3(0, h, 0);
pjRot.y = ClampAngle(pjRot.y, actualRot - 90, actualRot + 90);
transform.eulerAngles = pjRot;
It only works well when players rotation is 0, but if it's orientated to the left, right or any other direction it get's a little crazy.
I have been trying to look other posts or make it by myself, but i can not achive what i want. Let me know if i'm doing it wrong or if I need another method. Thanks
you can also do like the below
float rAngle = 0.0f;
private void Update()
{
rAngle += Input.GetAxis("Horizontal") * rotationSpeed;
rAngle = $$anonymous$$athf.Clamp(rAngle, -90.0f, 90.0f);
rNode.rotation = Quaternion.AngleAxis(rAngle, Vector3.up);
}
It just keeps initial rotation clamp. Even if I'm at 180 degrees it keeps the range between -90 and 90, ins$$anonymous$$d of clamp rotation between 90 and 270. What I need is to clamp rotation plus $$anonymous$$us 90 degrees, regardless it's actual rotation.
in the second line change the clamp values to whatever you want. like
rAngle = mathf.clamp(rAngle,90.0f,270.0f);
Your answer
Follow this Question
Related Questions
Rotation before 0 and after 360 0 Answers
Object don't rotate correctly 1 Answer
Clamp a 2D object controlled by the mouse 0 Answers
Is this a good way to Clamp a Rotation? 2 Answers
Clamping a camera with weird results 0 Answers