Why doesn't this clamp work?

Pretty new to unity and coding, sorry for the ugly code. But I was trying to make the barrel of a cannon point towards the mouse and have a limited rotation. Have been trying to figure out why this won’t work for several hours and haven’t been able to find any code online that works for specifically this.

      float q = Input.GetAxis("Mouse X");
      float e = Input.GetAxis("Mouse Y");
      float r = Mathf.Clamp(e, -45, 45);
      transform.Rotate(r, 0, 0);

This is under a void update function.
This is what I have got currently, have tried a lot of similar lines of code, and have done a lot of research and can’t figure out what’s wrong with this. I know that q is not currently doing anything, had it like that for testing. Thanks. Would help if you explain why it won’t work, so I won’t make a similar mistake again.

Because transform.Rotate is a relative operation. It ADDS a certain rotation to the existing rotation of the object. You want to SET the rotation, like this:

      float q = Input.GetAxis("Mouse X");
      float e = Input.GetAxis("Mouse Y");
      float r = Mathf.Clamp(e, -45, 45);
      transform.rotation = Quaternion.Euler(r, 0, 0);
1 Like