- Home /
Limit rotation (Horizontal and vertical input)
Hello, So I need to limit the rotation on an object that is controlled by keyboard to rotate on both the Z and X axis. I would like to be able to limit how much the object rotates to 20 degrees either direction from the 0 point of rotation. So this would mean the object could rotate -20 degrees and +20 degrees on both x and z.
I have been trying like crazy to use the Mathf.Clamp, however I have yet to get it to work.. things just start popping all over the place.. I could really use a hand on a best method for doing this. Thank you so much in advance.
Here is my code:
function Start () {
}
var rotateObject: GameObject;
function Update () {
if (Input.GetAxis("Horizontal") > 0) {
rotateObject.transform.localEulerAngles.z -= 10 * Time.deltaTime; //right
}
if (Input.GetAxis("Horizontal") < 0) {
rotateObject.transform.localEulerAngles.z += 10 * Time.deltaTime; //left
}
if (Input.GetAxis("Vertical") > 0) {
rotateObject.transform.localEulerAngles.x += 10 * Time.deltaTime; //forward
}
if (Input.GetAxis("Vertical") < 0) {
rotateObject.transform.localEulerAngles.x -= 10 * Time.deltaTime; //backward
}
}
Answer by hvilela · Sep 18, 2012 at 03:38 AM
Do like this:
var tmp = rotateObject.transform.localEulerAngles.z - 10 * Time.deltaTime;
rotateObject.transform.localEulerAngles.z = Mathf.Clamp(tmp, -20, 20);
EDIT:
var tmp = rotateObject.transform.localEulerAngles.z - 10 * Time.deltaTime;
if (tmp < 20 || tmp > 340) {
rotateObject.transform.localEulerAngles.z = tmp;
}
Unfortunately this is not working as intended. When I enter this in, and I try to rotate the object (in this example I am trying to rotate the z into the negative) it pops from 0 rotation when I begin, all the way to +20 on the other direction. after that, if I move a little past +20 and press a key to go the opposite direction, it immediately pops to -20,Part of the problem might be that the rotation for this object when played goes 0,+1,+2, etc going left (pos z) then goes 0,359,358,357,etc going the opposite direction on z.
I want the object to smoothly rotate, starting at the 0 point from 0 to positive 20, then from 0 to -20 degrees of the current position, however in this case it seems to mean 340 degrees. With this solution it seems to just snap to both locations, with no smoothing of the movement...
$$anonymous$$y answer was edited. Check if it solve your problem.
Thank you so much, this works perfectly! Still new to scripting, so I really appreciate the help.
Your answer
Follow this Question
Related Questions
get euler rotation from horizontal and vertical axis values 1 Answer
Possible To Add Move Functions To Camera? 2 Answers
Simple controls for a helicopter 2 Answers
rotate the camera in the z axis 1 Answer
limit AddRelativeForce 1 Answer