Camera yaw gives 180° in one direction but 0° when player faces opposite direction

Godot Version

4.6

Question

I want to limit the horizontal rotation (yaw) of the player’s camera to the range [-180°, 180°].
When the camera moves from the center to the left, the maximum angle must be +180°. When it moves to the right, the maximum angle must be -180°.
To move from one extreme to the other, the rotation must pass through 0°.
However, I have a problem: the result currently depends on the player’s orientation in the world.

For example:
If the player is facing north and the camera is looking south, I get ±180°.
But if the player is facing south and the camera is looking north, the returned angle is 0° instead of ±180°.

I want the camera rotation to always be relative to the direction the player is facing, and to produce a consistent angle in the range [-180°, 180°], regardless of whether the player is looking north, south, east, or west.

Please help me, I’ve been trying to solve this problem for two days.

What happens when the player rotates more than the constrain would allow?

I’m just going to add some UI effects to prevent the player from turning around, but without blocking them abruptly.

Project player right and look vectors and camera look vector into horizontal plane and normalize them. Take the dot product between camera look and player right, this and previous frame. If the dot product changed sign and the dot product between player look and camera look is less than 0 - don’t rotate the camera this frame.