# Restrict Up/Down rotation, detect angle upwards/ downwards

I have an object using Quaternion.LookRotation() to look at target object, I would like to be able to restrict the rotation by being able to set the range that the object can rotate at, for example from 45 degrees to 180 degrees, this would mean the object does not rotate lower than 45 degrees and does not rotate higher than 180 degrees, currently my code looks like this:

void Start(){
baseRotation = transform.localEulerAngles;
}
Vector3 targetPos = Target.position;
Vector3 dif = targetPos - obj.position;
dif.z = 0;

Quaternion lookAngle = Quaternion.LookRotation(dif, obj.up);
print("angle: "+ Quaternion.Angle(lookAngle, Quaternion.Euler(baseRotation)));
if (Quaternion.Angle(lookAngle, Quaternion.Euler(baseRotation)) < rangeMax - rangeMin)
{
targetR = lookAngle;
}
obj.rotation = Quaternion.Lerp(obj.rotation, targetR, Time.deltaTime * 100);
}


However this code makes sure that rotation both upwards and downwards equally does not exceed the same angle, which is not quite what I want, as I said I would like to set the start angle and the end angle. How would I do that? Could you post the code that would give me an idea?

Thanks in advance!

## 2 Answers

With the somewhat limited info you wrote, you could try:

1. Calculate 3D points (or 2D) for the edge Target.position's, by the allowed maximum angles (-45 and +180 degrees).
2. Resolve a point exactly in the middle of those two points.
3. Grab the Quaternion.LookRotation for that point.
4. Calculate the maximum diverge angle by: (-45 + 180) / 2 = 112.5 degrees.
5. Always compare (using Quaternion.Angle) to that quaternion.

The only diference would be that -45 and +180 degrees now are relative to an angle 67.5 degrees (instead of 0), so diverging in either direction with 112.5 degrees will hit the limit. Ie. you don't need to know in which direction it happened, as you "are in the middle".

To clamp a rotation on just one axis:

1. convert your quaternion to euler angles
2. use Mathf.clamp on the axis you want to limit.
3. convert it back to a quaternion

Example:

 Vector3 eulerRot = lookAngle.eulerAngles;
eulerRot.y = Mathf.clamp(eulerRot.y, -45f, 180.0f);
lookAngle.eulerAngles = eulerRot;

• I have just inserted your bit of code and it doesn't seem to work, the object (with lookrotation script) just looks to the right or front and as I move the target it vibrates or snaps to a different position. – Vadim Tatarnikov Apr 2 '17 at 13:31