Unity2D – Rotation of gun following mouse error when parent ‘player’ object rotates

I have a bug I’ve been trying to fix with the rotation of a gun object that follows the mouse position but has issues when the parent object player rotates. Example:

Example of rotation error

The player has a gravity script to keep them aligned with the ‘planet’ as you walk around it. The gun as a child of the player, is supposed to always rotate to point at where the mouse is (sorry you can’t see it in the gif). The gun normally flips itself at 90 and -90 (top and bottom), and flips the player to face the same side the mouse is on.

The problem is that the player rotates to stay aligned with the planet, but the 90 and -90 angles that the gun bases flipping itself and the player off of course don’t rotate.

Here’s my code for the gun:

         Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;           difference.Normalize();           float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;            float startRotation = rotationZ + offset;            float shotRotation = startRotation + Random.Range(-scatter, scatter);            transform.rotation = Quaternion.Euler(0f, 0f, startRotation);            //Flip the gun at top and bottom           if (rotationZ < -90 || rotationZ > 90)           {               if (player.transform.eulerAngles.y == 0)               {                   transform.localRotation = Quaternion.Euler(180, 0, -rotationZ + offset);               }               else if (player.transform.eulerAngles.y == 180)               {                   transform.localRotation = Quaternion.Euler(180, 180, -rotationZ + offset);               }           }            //Use gun rotation to set player direction           //left           if (rotationZ >= -90f || rotationZ <= 90f)           {               animator.SetFloat("Vertical", 0);               animator.SetFloat("Horizontal", -1);           }           //right           if (rotationZ <= -90f || rotationZ >= 90f)           {               animator.SetFloat("Vertical", 0);               animator.SetFloat("Horizontal", 1);           }