class_name PawnCamera extends Camera3D


var target
var player_offset : Vector3

@export var decay = 0.9  # How quickly the shaking stops [0, 1].
@export var max_offset = Vector2(2, 1.5)  # Maximum hor/ver shake in pixels.

@export var noise : FastNoiseLite
var noise_y = 0

var trauma = 0.0  # Current shake strength.
var trauma_power = 2  # Trauma exponent. Use [2, 3].
	
func _ready() -> void:
	randomize()
	noise = FastNoiseLite.new()
	noise.seed = randi()
	
@rpc("any_peer", "call_local", "reliable")
func register_pawn(id : int) -> void:
	set_multiplayer_authority(id)
	if id == Multiplayer.id:
		make_current()
	target = Game.level.pawns[id]
	target.camera = self
	player_offset = position - target.global_position
	

func add_trauma(amount):
	trauma = min(trauma + amount, 1.0)
	
func _process(delta: float) -> void:
	if target:
		global_position = target.global_position + player_offset
	if trauma:
		trauma = max(trauma - decay * delta, 0)
		shake()
	else:
		h_offset = 0
		v_offset = 0
		
func shake():
	noise_y += .1
	var amount = pow(trauma, trauma_power)
	var n_val = noise.get_noise_2d(noise.seed*2, noise_y)
	h_offset = max_offset.x * amount * randf_range(-1, 1)
	v_offset = max_offset.y * amount * randf_range(-1, 1)
	print("%f %f" % [h_offset, v_offset])
