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:

  1. 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…

  2. 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?

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

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.