- Home /
Rotate an object with angle limit
I want to rotate an object with arrow keys. Here is the code I used for the rotation ,
if(Input.GetKey(KeyCode.UpArrow))
{
transform.Rotate(Vector3.right,1,1);
}
if(Input.GetKey(KeyCode.DownArrow))
{
transform.Rotate(Vector3.left,1,1);
}
if(Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(Vector3.up,1,1);
}
if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(Vector3.down,1,1);
}
This works,
But, I want to limit the rotation of this object, which is a disc on top-down view. Example, if I press uparrow, the object should only be able to rotate till 15deg towards Vector3.right. Same with all the other keys.
How do I achieve this?
Thanks in advance.
Answer by aldonaletto · Aug 07, 2012 at 03:16 AM
The best way to control rotation precisely in Unity is to "rotate" the angles mathematically and assign them to transform.eulerAngles each Update. To do this, save the initial eulerAngles in a Vector3 variable (initialAngles) at Start, and have another Vector3 variable (curAngles) to show the rotation relative to initialAngles. Increment or decrement curAngles with the controls and clamp them to the limits, then set transform.eulerAngles to initialAngles + curAngles. In order to make the rotation frame rate independent, make the increments/decrements proportional to Time.deltaTime:
var rotSpeed: float = 30; // rotation speed in degrees/second private var initialAngles: Vector3; private var curAngles: Vector3; // rotation relative to initial direction
function Start(){ initialAngles = transform.eulerAngles; curAngles = Vector3.zero; }
function Update(){ if (Input.GetKey("up")){ curAngles.x -= rotSpeed Time.deltaTime; } if (Input.GetKey("down")){ curAngles.x += rotSpeed Time.deltaTime; } if (Input.GetKey("left")){ curAngles.y -= rotSpeed Time.deltaTime; } if (Input.GetKey("right")){ curAngles.y += rotSpeed Time.deltaTime; } // limit the angles: curAngles.x = Mathf.Clamp(curAngles.x, -15, 15); curAngles.y = Mathf.Clamp(curAngles.y, -15, 15); // update the object rotation: transform.eulerAngles = initialAngles + curAngles; }
Thanks, it worked. I wasn't working on this project for a while and completely forgot that I got an answer from you. sorry for the delay. :)