# Clamping or testing an angle between objects.

I am working on a turret and, thus far, both the AI and player control is working; however I need to clamp the elevation angles of the gun.
Here is the code I’m using for the gun’s elevation (rotation around the Y axis is done elsewhere).

var firingVector : Vector3 = (parentScript.currentWeaponTarget.transform.position - transform.position);
xRotation = Quaternion.LookRotation(firingVector, transform.parent.right);
Rotation = Quaternion.Euler(xRotation.eulerAngles.x, 0, 0);
gunPipe.transform.localRotation = Quaternion.RotateTowards(gunPipe.transform.localRotation, xRotation, maximumElevationVelocity);

Would there be anyway for me to ether clamp the rotation or create an if statement to test the angle? The latter is my preferred method.

You just have to limit the rotation according to the max/min angle you want, before you set transform.localRotation. You can do this by using Mathf.Clamp with the minimum/maximum angle. This example limits the rotation to 30 degrees to each direction. Since these is localRotation, the rotation is always relative to the object’s parent.

var maxAngle = 30;

var firingVector : Vector3 = (parentScript.currentWeaponTarget.transform.position - transform.position);
xRotation = Quaternion.LookRotation(firingVector, transform.parent.right);
Rotation = Quaternion.Euler(xRotation.eulerAngles.x, 0, 0);
gunPipe.transform.localRotation = Mathf.Clamp(Quaternion.RotateTowards(gunPipe.transform.localRotation, xRotation, maximumElevationVelocity), -maxAngle, maxAngle); // clamp angle between -maxAngle and maxAngle.