@Philipp's answer is correct but I want explain more about limiting
if you want rotate the object only once after a key press you should use Input.GetKeyDown In Update function
but if you want limit rotation between two value min_max you can use Mathf clamp
function clamp(x, min, max):
if (x < min) then
x = min;
else if (x > max) then
x = max;
return x;
end clamp
Mathf.Clamp(float value, float min, float max);
using UnityEngine;
using System.Collections;
public class RotationController : MonoBehaviour {
void Update () {
transform.rotation = Quaternion.Euler(new Vector3 (
transform.rotation.eulerAngles.x,
transform.rotation.eulerAngles.y,
Mathf.Clamp (transform.rotation.eulerAngles.z, -3, 3)));
if (Input.GetKeyDown(KeyCode.D))
transform.Rotate(0, 0, 3);
if (Input.GetKeyDown(KeyCode.A))
transform.Rotate(0, 0, -3);
}
}
in other way you can use Quaternion to limiting
Quaternion definition:
using UnityEngine;
using System.Collections;
public class degree : MonoBehaviour {
public float w,x,y,z;
public float a = 0;
void Start(){
a = a / 360 * (float)Mathf.PI * 2;
w = Mathf.Cos (a / 2);
x = Mathf.Sin (a / 2);
y = Mathf.Sin (a / 2);
z = Mathf.Sin (a / 2);
print (a);
gameObject.transform.rotation = new Quaternion (w,x,y,z);
}
}
you should know about
Degrees 30°
Radians(exact)π/6
Radians(approx) 0.524
learning link
so you can limit rotation:
void Update () {
print (transform.rotation.z);
if (Input.GetKeyDown(KeyCode.D) && transform.rotation.z <0.02617695)
transform.Rotate(0, 0, 3);
}