# Rotate tank turret on key press until specific angle then stop rotation

Hi, I’m currently learning C# and Unity with a 2D tank game I’m building for experience. I was able to write a script for my tank that allows the turret to rotate over the z axis 2f and -2 if you hold R or T. The problem is I want the nose to stop rotating at a certain degree (36 and 348) so that the angle of the shot being fired is limited and the nose doesn’t come off of the tank and look strange. Below is what I have so far to make the turret move, but I don’t know where to go from there. Any advice would be great. Thank you

``````[SerializeField]
private float noseAngleP;

[SerializeField]
private float noseAngleN;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void FixedUpdate () {
tankRotate ();
tankStop ();

}

private void tankRotate()
{
if (Input.GetKey (KeyCode.R)) {
transform.Rotate(0,0,2f);

}

if (Input.GetKey (KeyCode.T)) {
transform.Rotate (0, 0, -2f);
}

}

private void tankStop()
{

if (noseAngleP > Quaternion.eulerAngles.z) {
transform.Rotate (0, 0, 0);
}

if (noseAngleN < Quaternion.eulerAngles.z) {
transform.Rotate (0, 0, 0);
}
}
``````

}

@schladog - Having a look at your script, here are a couple suggestions:

• I’m not sure how your private variables noseAngleP and noseAngleN are getting set (perhaps you’re doing that elsewhere). You could make those public variables in your script and then set the values in the Inspector in Unity, that way you wouldn’t have to change the code if you want to make adjustments to the the angles.

• I would check for limiting the rotation in your tankRotate function similar to the code below. Basically, you don’t let the turret move if it violates the minimum / maximum values you’ve set instead of allowing the rotation and then trying to stop it in the tankStop function.

private void tankRotate() {

`````` if (Input.GetKey (KeyCode.R) && noseAngleP < Quaternion.eulerAngles.z) {
transform.Rotate(0,0,2f);
}

if (Input.GetKey (KeyCode.T) && noseAngleN > Quaternion.eulerAngles.z) {
transform.Rotate (0, 0, -2f);
}
``````

}