# Unity 3D - Confine a gun rotation within certain degrees

I am having troubles making my gun rotate up and down, and have limits, for example, I want the down limit to be 0 degrees, and the up limit to be 90 degrees.

Currently I can't figure out how to define that, and when the gun gets to one of the extremes, it gets stuck there and doesn't want to go back. Whats wrong?

Here's how I rotate the gun using an on-screen joystick

float lookAxisX = CrossPlatformInputManager.GetAxisRaw("VerticalLook");

if ((transform.localEulerAngles.x <= 360 && transform.localEulerAngles.x > 270) ||
(transform.localEulerAngles.x >= 0)
) {
transform.localEulerAngles += new Vector3(-lookAxisX * 2f, transform.localEulerAngles.y, transform.localEulerAngles.z);
}

Debug.Log("transform: " + transform.localEulerAngles);


Also right now, when the gun is at the default rotation (facing forward, its X angle is 0, and when it rotates up, it goes from 0 to 359,9, and then at 270 it gets stuck

First, it won't solve your problem, but there are a few general problems with your code.

1. The conditions for your if branch will always be true if transform.localEulerAngles.x >= 0 and <= 360. The > 270 part is redundant since if x is less than 270, it is still possible to be >= 0.

2. If x is 0 and lookAxisX is > 0, then adding -lookAxisX will make x < 0, meaning your if branch will never be enter again, unless you reset the rotation somehow. Vice versa if x = 359.9 and lookAxisX is < 0.

That said... it's easier to use Mathf.Clamp(), as Marc Uberstein pointed out in his answer.

You also need to keep track of your angles separately from the transform, since as soon as you apply the angles to localEulerAngles, the 360 value will be reset to 0 and cause problems. That doesn't happen if you store it separately.

Tip: 360 degrees == 0 degrees! which is why it maxes at 359.9 :)

Try this:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

public float speedX = 2.0f;
private float lookAxisX = 360.0f;

void Update () {
lookAxisX -= speedX * CrossPlatformInputManager.GetAxisRaw("VerticalLook");

lookAxisX = Mathf.Clamp(lookAxisX, 270, 360);
transform.localEulerAngles = new Vector3(lookAxisX, transform.localEulerAngles.y, transform.localEulerAngles.z);

Debug.Log("transform: " + transform.localEulerAngles);
}
}


You can always try to use the clamp method: Ref: http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

Example

transform.localEulerAngles = new Vector3(Mathf.Clamp(transform.localEulerAngles.x, 0f, 90f), 0, 0);


**This is just a push in the right direction (above is untested)