How to Make a Camera Rotate with the Mouse Godot?

Add a `Camera3D` as a child of a `Node3D` or `CharacterBody3D`

Attach a script to the parent node or the camera

Capture the mouse in `_ready()`:

`Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)`

Store rotation values:

`var yaw := 0.0`

`var pitch := 0.0`

In `_input(event)`, check for mouse motion:

`if event is InputEventMouseMotion:`

Update rotation from mouse movement:

`yaw -= event.relative.x * sensitivity`

`pitch -= event.relative.y * sensitivity`

Clamp vertical rotation:

`pitch = clamp(pitch, deg_to_rad(-89), deg_to_rad(89))`

Apply rotation:

`rotation.y = yaw`

`camera.rotation.x = pitch`

Use a small sensitivity value like `0.002`

Example script:

`extends Node3D`

`@onready var camera: Camera3D = $Camera3D`

`var yaw := 0.0`

`var pitch := 0.0`

`var sensitivity := 0.002`

`func _ready():`

` Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)`

`func _input(event):`

` if event is InputEventMouseMotion:`

` yaw -= event.relative.x * sensitivity`

` pitch -= event.relative.y * sensitivity`

` pitch = clamp(pitch, deg_to_rad(-89), deg_to_rad(89))`

` rotation.y = yaw`

` camera.rotation.x = pitch`

To release the mouse:

`Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)`

Suggested for You

Trending Today