- Home /
How to restrict rotation
Hello, I'm trying to set limits to my rotation script, for instant, when I press "a" to rotate left and it reaches -90 it stops, and when I press "d" to rotate right and it reaches 90 it stops there, I know it is simple, but I can't seem to make it work, even tho I tried all day with no success.. I'd appreciate some help! :)
Here is my script:
#pragma strict
public var speed : float = 1f;
function FixedUpdate ()
{
if (Input.GetKey("d"))
transform.Rotate(-Vector3.up, speed * Time.fixedDeltaTime);
if (Input.GetKey("a"))
transform.Rotate(Vector3.up, speed * Time.fixedDeltaTime);
}
Answer by FlaSh-G · Jul 23, 2017 at 09:46 PM
Try this:
private var rotation = 0f;
function FixedUpdate()
{
if(Input.GetKey("d"))
rotation += speed * Time.deltaTime;
if(Input.GetKey("a"))
rotation -= speed * Time.deltaTime;
rotation = Mathf.Clamp(rotation, -90, 90);
var rot = transform.localEulerAngles;
rot.y = rotation;
transform.localEulerAngles = rot;
}
Watch out! You are modifying the y component of the quaternion property, should be better to change the local/global euler angle property.
Answer by NejoFTW · May 23 at 09:18 AM
If you need a simple Y rotation limit this kind of works for me, example for camera rotation limited on Y axis. Attach component to camera, replace the "InputY" float with your input value from -1 to 1 and make a float for speed and rotationLimit variables and you should be good to go...
public void RotateCamera()
{
Vector3 cameraEuler = transform.rotation.eulerAngles;
if (cameraEuler.y > 180)
{
cameraEuler.y -= 360;
}
float desiredRot = cameraEuler.y + (inputY * speed);
if (desiredRot > -rotationLimit && desiredRot < rotationLimit)
{
transform.Rotate(Vector3.up, inputY * speed);
}
}