What is wrong with clamping?
Hi, I have written this simple line of code, that should rotate an empty and drag the camera behind with a 20° offset.
void Update () {
// Moving Parent and Camholder
parentMesh.transform.Rotate (0,Input.GetAxis ("Mouse X") * Time.deltaTime * mouseSensivety, 0);
//Moving Cam
cam.transform.eulerAngles = new Vector3(Mathf.Clamp(cam.transform.eulerAngles.x, parentMesh.transform.eulerAngles.x - 20f, parentMesh.transform.eulerAngles.x + 20f), Mathf.Clamp(parentMesh.transform.eulerAngles.y, parentMesh.transform.eulerAngles.y - 20f, parentMesh.transform.eulerAngles.y + 20f), 0);
}
But it simply rotates the Camera instantly, as if I directly applied the .Rotate to it. What can I do to have it working right?
Answer by UnityCoach · Feb 24, 2017 at 08:39 PM
What do you expect? Transform.Rotate()
rotates the transform instantly. Maybe you want to use .rotation = Quaternion.RotateTowards ()
As for Mathf.Clamp ()
, it simply limits a value between a lower and upper limits. So here again, this will happen instantly. Maybe you want to use Mathf.Lerp ()
?
The Transform.Rotate()
only rotates a Empty, so it shouldn't move the camera. Than the Clamping only limits the Rotation of the Camera to 20° off the Empty.That should allow you to move the without moving the Camera (To a certain degree).
Is the Camera parented to the parent$$anonymous$$esh object at all?
I also once used the line Transform.EulerAngels = new Vector3 ($$anonymous$$athf.Clamp(Transform.EulerAngles.x, -90, 90), Transform.EulerAngles.x, 0);
to prevent the camera from over rotating, and it didn't work either. What could be wrong about that? (It once worked for me in this exact way)
This is a gimbal lock problem. 355 degrees + 20 = 375, which results in 15, like 5 degrees - 20 = -15, which results in 345. While you can clamp values between 30 and 70, you can't clamp between 345 and 15. If you search for "gimbal lock", you'll find plenty of methods to prevent this. Let me know if you're stuck with this.
Your answer
Follow this Question
Related Questions
Need help clamping rotations to a range 0 Answers
What does this error message mean and how do I fix it? 1 Answer
C# Mouse Look Script | Why does the Y Axis Work but not the X Axis? 1 Answer
Clamping Wrapping Rotation to Fixed Angle 0 Answers
Standard mouselook X-rotation clamp doesn't work with standard rigidbodyfirspersoncontroller 0 Answers