I'm trying to get a simple cannon to rotate to point at the mouse, but I only want it to follow the mouse for 180 degrees and then stop following the mouse, and pick up again when the player re-enters the 180-degree area. I got the cannon to follow the user's mouse but when I tried to camp it to the 180-degree area I found it worked for one side, but when I went to the other it "teleported" to the other side.
I video to explain my issue: https://i.sstatic.net/ZVNCn.jpg Sorry about the crude graphics, frame rate, and the software doesn't show my mouse making things more difficult, but as you can see, the clamp works fine when I move my mouse to the right, but when I move it to the left it "teleports" or instantly moves to teh right no matter where my mouse is.
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;
float finalRotation = angle + rotationOffset;
// I have tried both the normal Mathf.Clamp and the if statments below and I get the exact same result.
//finalRotation = Mathf.Clamp(180, 0, finalRotation);
if (finalRotation >= 89f)
{
finalRotation = 89f;
Debug.Log("Left");
}
else if(finalRotation <= -89f)
{
finalRotation = -89f;
Debug.Log("Right");
}
transform.rotation = Quaternion.Euler(0, 0, finalRotation);
}
I don't know if this might be a bug in Unity, But I've spent days trying to fix it, I'm tired, I'm stressed, I don't know how to fix it.

