- Home /

# Clamp Rotation Problem

Hey guys, after a long time searching about a way to Clamp the rotation, I finally found out something. Everything's working Ok, except for one thing. The cannon I'm using for a game need to rotate along eulerAngles.x axis. The Start X rotation is 270, but even if I move it up or down, the rotation increase it value.

For exemple, when I move mouse up, the rotation increase from 270 to 345(value I want to clamp). And when I move mouse down, the rotation increase the same value, from 270, to 345.

What I want is that when I move mouse up, the rotation increase and when I move mouse down, the rotation decrease, so that way my Clamp should work correctly. Here's the code:

var angles: Vector3 = Vector3.zero;

var rotationVelocity: float;

function Start() {

angles.y = transform.eulerAngles.y;

angles.x = transform.eulerAngles.x;

angles.z = transform.eulerAngles.z;

}

function Update() {

print(transform.eulerAngles.x); // that's how I found out the problem

if(Input.GetAxis("Mouse Y") > 0) {

angles.x += rotationVelocity * Time.deltaTime;

angles.x = Mathf.Clamp(angles.x, 270, 345);

transform.eulerAngles.x = angles.x;

}

if(Input.GetAxis("Mouse Y") < 0) {

angles.x -= rotationVelocity * Time.deltaTime;

angles.x = Mathf.Clamp(angles.x, 270, 345);

transform.eulerAngles.x = angles.x;

}

}

Sorry about my English, I'm brazilian. Thanks from now!

Your code works fine for me. It isn't the most efficient set up ever, but I just pasted that script onto a cube, and got the behavior you just described to me that you wanted.

If you want slightly cleaner code, then you can take Input.GetAxisRaw() to get the sign of the axis movement then multiply by that.

```
function Update() {
var input = Input.GetAxisRaw("Mouse Y");
//returns -1 , 0 , or 1 based on movement.
if(input != 0) {
//We really only need to do the rest if we actually moved some.
angles.x += rotationVelocity * Time.deltaTime * input;
angles.x = Mathf.Clamp(angles.x, 270, 345);
transform.eulerAngles.x = angles.x;
}
}
```

**Answer** by GutoThomas
·
Oct 10, 2011 at 04:22 AM

Thanks! I could find out and solve the problem!

Very nice tip to make the code cleaner! ;)

Thank you again!

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.