- 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("$$anonymous$$ouse 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 = $$anonymous$$athf.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!