Capturing the Mouse for a First-Person Controller
A first-person game needs a slightly different approach to mouse input than a typical desktop application.
Normally, the mouse cursor moves around the screen. In a first-person game, however, we don't really care about the cursor's position. We care about how much the mouse moved.
Godot provides a convenient way to handle this:
func _ready() -> void:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
When the mouse is captured, the operating system's cursor is effectively hidden and locked to the game window.
More importantly, Godot provide us with relative mouse movement through InputEventMouseMotion.
Our controller receives these events in _input():
func _input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
# Mouse movement goes here
The important property is:
event.relative
This contains the mouse movement since the previous event.
For example:
Mouse moved right → relative.x is positive
Mouse moved left → relative.x is negative
Mouse moved up → relative.y is negative
Mouse moved down → relative.y is positive
This is exactly what we need for a first-person camera.
Instead of asking:
"Where is the mouse?"
we can ask:
"How far did the mouse move?"
That makes the mouse input independent of the screen resolution and the actual position of the cursor.