2 class_name CameraHandler
6 @export_range(1.0, 10.0) var camera_distance := 3.0
8 @export var allow_manual_control := false
10 @export_range(0.0, 1.0) var mouse_sensitivity := 0.2
11 @export_range(0.0, 1.0) var mouse_sensitivity_x := 1.0
12 @export_range(0.0, 1.0) var mouse_sensitivity_y := mouse_sensitivity_x / 2
14 @export_range(0.0, 1.0) var joystick_sensitivity := 1.0
15 @export_range(0.0, 10.0) var joystick_sensitivity_x := 4.0
16 @export_range(0.0, 10.0) var joystick_sensitivity_y := joystick_sensitivity_x / 2
18 @export_group("Tracking")
19 @export var tracking_node: Node3D
20 @export_range(0.0, 1.0) var tracking_lock := 0.5
23 @onready var spring: SpringArm3D = $SpringArm3D
24 @onready var camera: Camera3D = $SpringArm3D/Camera3D
27 # Called when the node enters the scene tree for the first time.
28 func _ready() -> void:
29 spring.spring_length = camera_distance
32 # Called every frame. 'delta' is the elapsed time since the previous frame.
33 func _process(delta: float) -> void:
34 spring.spring_length = lerp(
35 spring.spring_length, camera_distance, delta
38 global_position = lerp(
40 tracking_node.global_position,
41 tracking_lock * delta * 4
45 func update(input: InputPacket, delta: float):
46 if not allow_manual_control:
49 var camera_input_direction := input.camera_input_direction
51 if input.camera_input_method == CameraInput.MOUSE:
52 camera_input_direction *= Vector2(
53 mouse_sensitivity_x, -mouse_sensitivity_y
55 elif input.camera_input_method == CameraInput.JOYSTICK:
56 camera_input_direction *= Vector2(
57 joystick_sensitivity_x, -joystick_sensitivity_y
58 ) * joystick_sensitivity
60 # vertical camera rotation
61 rotation.x += camera_input_direction.y * delta
62 rotation.x = clamp(rotation.x, -PI / 6, PI / 3)
64 # horizontal camera rotation
65 rotation.y -= camera_input_direction.x * delta
68 # Get the XZ input direction based on player's input relative to the camera
69 func get_xz_direction_relative_to_camera(d: Vector2) -> Vector2:
71 var forward := camera.global_basis.z
72 var right := camera.global_basis.x
73 var dir3 := forward * d.y + right * d.x
74 return Vector2(dir3.x, dir3.z).normalized() * d.length()