Prevent negative angles

Hello

I try to make my first game; two cannons facing each other. The cannons rotate in z axis by hitting up and down arrows. My target is to limit the rotation angle between 0 and 60 degrees. Problem is that while the upper threshold works fine the lower one doesn’t. I still get negative degrees. How can i prevent that? Here is my code:

public class Cannon : MonoBehaviour
{
Vector3 z_angle_up = Vector3.forward; //rotates the game object around z axis
Vector3 z_angle_down = Vector3.back;

private void Update()
{
    Rotate_up();
    Rotate_down();
 } 

private void Rotate_up()
{
    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        if(gameObject.transform.rotation.eulerAngles.z <=60)
        gameObject.transform.Rotate(z_angle_up * 50 * Time.deltaTime);
    }
}

private void Rotate_down()
{
    if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        if (gameObject.transform.rotation.eulerAngles.z >0)              
            gameObject.transform.Rotate(z_angle_down * 50 * Time.deltaTime);   
    }
   
}

}

Hi Chris,

You could clamp the rotation value with Mathf.Clamp. Just bear in mind that transform.rotate is of type Quaternion, so you’ll have to convert the Quaternion to Euler angles, clamp the z-component and convert the Euler angles back to a Quaternion. You can find useful methods in the API.

Good luck! :slight_smile:

This topic was automatically closed after 13 days. New replies are no longer allowed.

Privacy & Terms