- Home /
How can I clamp the object up and down rotation from 0 to -90?
Image 1
Image 2
I'm trying to rotate an object to left, right, up and down. The left and right rotation works. But the up and down rotation clamp is not working. What am I doing wrong?
using UnityEngine;
public class RotateHelper : MonoBehaviour
{
public bool rotateUp;
public bool rotateDown;
public bool rotateLeft;
public bool rotateRight;
public Transform pivotTransform;
public float rotateSpeed;
void Update()
{
if (rotateUp)
{
pivotTransform.Rotate(-(Time.deltaTime * rotateSpeed), 0, 0, Space.Self);
}
if (rotateDown)
{
pivotTransform.Rotate(Time.deltaTime * rotateSpeed, 0, 0, Space.Self);
}
Vector3 pivotRotation = pivotTransform.eulerAngles;
pivotRotation.x = Mathf.Clamp(pivotRotation.x, -90.0F, 0.0F);
pivotTransform.eulerAngles = pivotRotation;
if (rotateLeft)
pivotTransform.Rotate(0, -(Time.deltaTime * rotateSpeed), 0, Space.World);
if (rotateRight)
pivotTransform.Rotate(0, Time.deltaTime * rotateSpeed, 0, Space.World);
}
}
Answer by normus28 · Apr 06, 2019 at 01:53 PM
It's because you are clamping quaternion angles and thats how Unity handles rotation by default because its faster, you can read about it here: https://docs.unity3d.com/ScriptReference/Quaternion.html
It's hard to understand so most people are translating quaternion to euler angles in code (standard x, y, z rotation) that is shown in the editor in the transform window). So you have to translate the angles to euler.
so Instead of using:
pivotRotation.x = Mathf.Clamp
Use:
rotationX = Mathf.Clamp (pivotRotation.eulerAngles.x, -90.0F, 0.0F);
pivot.rotation = Quaternion.Euler (rotationX, transform.eulerAngles.y, transform.eulerAngles.z);
Thanks! This link is also helpful: https://docs.unity3d.com/$$anonymous$$anual/QuaternionAndEulerRotationsInUnity.html
Your answer
Follow this Question
Related Questions
Restricting GameObject Rotation 1 Answer
How to rotate object slowly on only Z axis 2 Answers
Rotation with multiple objects 1 Answer
Rotate a moving object 0 Answers
Wonky Camera Behaviours 0 Answers