class_name TrackingCamera extends Camera3D
## Camera that tracks a target, maintaining a distance within parameters.

const ROTATION_ACCELERATION := 2.0
const POSITION_ACCELERATION := 4.0

@export var target: Node3D

@export var active := false

@export var min_distance := 0.5
@export var max_distance := 3.0


func _physics_process(delta: float) -> void:
	if not active:
		return

	# Update position
	var relative_position := global_position - target.global_position
	var distance := relative_position.length()
	if distance < min_distance:
		global_position = global_position.lerp(
			target.global_position + relative_position.normalized() * min_distance,
			delta * POSITION_ACCELERATION
		)
	elif distance > max_distance:
		global_position = global_position.lerp(
			target.global_position + relative_position.normalized() * max_distance,
			delta * POSITION_ACCELERATION
		)

	# Update rotation
	var target_basis := (
		Transform3D().looking_at(target.global_position - global_position, Vector3.UP).basis
	)
	global_basis = global_basis.slerp(target_basis, delta * ROTATION_ACCELERATION)
