How to have a gameobject only rotate 180 degrees

I have a cannon that can rotate 360 degrees, but I need it to only spin 180 degrees. How do I do that?
Here is my code:

public int rotationOffset = -90;

    // Update is called once per frame
    void Update()
    {
        var mouse = Input.mousePosition;
        var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
        var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
        var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle + rotationOffset);

    }

Try adding a Clamp right after the “var angle = …” line.

angle = Mathf.Clamp(angle, -90, 90);

You can change the clamp parameters to restrict it as needed, but I believe -90 to 90 will work for what you described. Good luck!

Probably check this thread 1

Hello, looks like you could add in an “if” statement of sorts to check the rotation and use it to halt the movement. However it looks like the answers before mine seem to be more accurate to your question. You can utilize the (cannon.transform.rotation.eulerAngles.z <= 90) code to achieve this same effect. You will probably need to add this either before or after the angle variable. Hopefully this is enough information as I realize this is a very short answer. Good luck!