Why does my camera's forward motion 'snap' to weird yaw angles?

Hi all,

I’ve been using this camera movement code (below) for ages now, but it has a strange bug that I’ve never been able to crack.

First, here’s the code. The variables pitch and yaw represent the camera’s yaw and pitch angles in degrees (in the 0-359 range).

public void moveCamForwardWithValue(float value)
	{		
		double cameraPitchInRadians = Math.toRadians(pitch);
		double cameraYawInRadians = Math.toRadians(yaw);
		float f = (float)Math.cos(cameraPitchInRadians);
		
		// prevent pitch angle from affecting forward speed
		if (!flyMode) { f = 1; }
		
		float addX = value  * f * (float)Math.sin(cameraYawInRadians);
		float addZ = value  * f * (float)Math.cos(cameraYawInRadians);
		float addY = value  * (float)Math.sin(cameraPitchInRadians);
		
		speedX -= addX;
		speedZ += addZ;
	    
	    if (flyMode) { speedY += addY; }
	}

What happens is that the user presses the ‘forward’ key (such as W) and moveCamForwardWithValue is called with a suitable input value.

Every frame the camera’s position is modified by the speedX and speedZ values (and speedY if flight mode is enabled).

The camera moves forward fine, but the YAW angle it moves along doesn’t always seem to be correct. Even stranger is that if I stay moving long enough, the movement ‘snaps’ to another yaw angle, almost as if it’s eventually snapping to the yaw angle it should’ve been on all along.

I should add that the flyMode variable is a toggle to allow the camera to travel up / down along the pitch vector (as if flying) for debugging purposes.

I hope all of the above makes sense, please let me know if any further clarification is needed.

Tearing my hair out on this one!

Thanks :slight_smile: