- Home /
Constrained rotation problem
Ok, so I have a flat board that can be rotated on the X and Z axis by the arrow keys, but can't be rotated more than 10 degrees either way.
I came up with this code:
private var newX : float;
private var newZ : float;
private var rot : Vector3;
function Update () {
rot = transform.eulerAngles;
newX = Mathf.Clamp(rot.x+Input.GetAxis("Vertical"),-10,10);
newZ = Mathf.Clamp(rot.z+Input.GetAxis("Horizontal"),-10,10);
transform.eulerAngles = Vector3(newX,0,newZ);
}
However I'm experiencing two problems:
Let's just pretend for the moment I'm not doing anything on the X axis, and I'm only trying to rotate along Z. Rotation along Z works fine as long as long as it's a positive number, but as soon as it goes below 0 (and I want it to go all the way down to -10), the board just goes crazy and starts moving uncontrollably until it's back in positives...
Along the X axis, nothing works at all. It just shakes uncontrollably no matter what the angle is.
I tested both these problems separatly (removing some code to test just one axis at a time), and I can't understand why it's doing this... Any ideas?
Answer by MasterTim · Oct 27, 2013 at 07:25 PM
private var newX : float;
private var newZ : float;
private var rot : Vector3;
function Update () {
rot = transform.localEulerAngles;
newX += Input.GetAxis("Vertical");
newX = Mathf.Clamp(rot.x,-10,10);
newZ += Input.GetAxis("Horizontal");
newZ = Mathf.Clamp(rot.z,-10,10);
transform.localEulerAngles = new Vector3(newX,0,newZ);
}
try this
That works great, cheers! (Had to replace "rot.x" and "rot.z" with "newX" and "newZ" but I figured that out quickly). Thanks for your help!
Answer by robertbu · Oct 27, 2013 at 07:39 PM
Your problem is that you are reading eulerAngles. Unity stores rotations internally as Quaternions and translates them back into eulerAngle representations. There are multiple eulerAngle representations for any given physical rotation, so you are not necessarily dealing with the angles you think you are. The easiest fix for the code above is to treat eulerAngles as write-only. Assuming your object starts with no rotation (0,0,0), this should work:
private var rot : Vector3 = Vector3.zero;
function Update () {
rot.x += Input.GetAxis("Vertical");
rot.x = Mathf.Clamp(rot.x,-10,10);
rot.z += Input.GetAxis("Horizontal");
rot.z = Mathf.Clamp(rot.z,-10,10);
transform.localEulerAngles = rot;
}
There is also an issue with your original code where you are clamping your rotation before you are setting the final rotation.
This works great just like the code from $$anonymous$$asterTim, thanks! :) Unfortunately I can't mark two answers as correct but I upvoted yours.
Your answer
Follow this Question
Related Questions
Bizzare problem with limiting camera veritcal rotation 2 Answers
Limit gameobject rotation to -480 and 480 degrees? 2 Answers
Clamping a wrapping rotation. 6 Answers
Edited mouselook script rotation clamp not working 0 Answers
Rotation not observing limits 1 Answer