# How to limit the rotation

I’m new to unity I’m creating a simple 2d game ,for that I want to know how to rotate an object using , when user presses down Q it should rotate in the anticlockwise direction and when E is pressed down it should rotate in the clockwise direction ,but I don’t want to let the user be able to rotate without a limit.i won’t the user to be able to rotate only between a180 degree angle clockwise and anticlockwise.really appreciate the help…

I’m not sure which axis you’re rotating around or what you consider to be acceptable rotation branches, but this will rotate an object you put it on between the given bounds on its a z-axis.

using UnityEngine;

public class LimitRotation : MonoBehaviour
{
private const float ROTATION_MIN = -90f;
private const float ROTATION_MAX = 90f;

// How much to rotate by
public float rotationSpeed = 5f;

// Update is called once per frame
void Update ()
{
// Get our current rotation and update based on input
Vector3 currentRotation = this.transform.eulerAngles;
float inputInfluence = 0;

// Apply the inputs
if (Input.GetKey (KeyCode.Q))
inputInfluence += this.rotationSpeed;
if (Input.GetKey (KeyCode.E))
inputInfluence -= this.rotationSpeed;

// Account for multiples
currentRotation.z = currentRotation.z % 360;

// Then account for wrapping
if (currentRotation.z > 180)
currentRotation.z -= 360f;

// Modify the rotation vector and reassign it
currentRotation.z = Mathf.Clamp (currentRotation.z + inputInfluence, ROTATION_MIN, ROTATION_MAX);
this.transform.rotation = Quaternion.Euler (currentRotation);
}
}