- Home /
Limiting a GameObject Rotation
I have a GameObject i am trying to rotate. i do not want it to rotate beyond a certain angle. Mainly because i do not want it to complete a 360 degree rotation.
Here is the code i have been using:
v=Input.GetAxis("VerticalMouse")*Time.deltaTime*sensetivity;
rotationDegree=inverted*v;
rotationDegree+=transform.rotation.x;
Mathf.Clamp (rotationDegree,minimumRotate,maximumRotate);
rotationDegree-=transform.rotation.x;
transform.Rotate (rotationDegree,0,0);
Regardless of whatever value i enter to minimumRotate and maximumRotate the objects can still complte a 360 angle rotation.
Answer by aldonaletto · May 07, 2013 at 11:28 AM
You're incorrectly using rotation.x: rotation is a quaternion, and its XYZW components have nothing to do with the rotation angles - you should use transform.eulerAngles instead:
v=Input.GetAxis("VerticalMouse")*Time.deltaTime*sensetivity;
rotationDegree=inverted*v;
var curX: float = transform.eulerAngles.x; // get the current X angle
rotationDegree += curX;
Mathf.Clamp (rotationDegree,minimumRotate,maximumRotate);
rotationDegree -= curX;
transform.Rotate (rotationDegree,0,0);
But be aware that reading eulerAngles may return weird values when there's some rotation about more than one angle - in this case, the rotation about axes Y and Z should be zero.
Thank you that was very helpful, also i upgraded the code to:
v=Input.GetAxis("Vertical$$anonymous$$ouse")*Time.deltaTime*sensetivity*inverted;
rotationDegree+=v;
rotationDegree=$$anonymous$$athf.Clamp (rotationDegree,$$anonymous$$imumRotate,maximumRotate);
transform.localEulerAngles=new Vector3(rotationDegree,0,0);
seems a bit cleaner this way.
Actually, this is the best way to do a well controlled rotation: "rotate" the angle mathematically and assign it to eulerAngles or localEulerAngles, as you're doing now. Always remember to set the 3 axes at once: assigning to one axis only is allowed in JS (not in C#), but may produce really weird results.