extends AnimatableBody2D

@export var shaking_target: Node2D
@export var shake_strength: float = 8.0
@export var shake_duration: float = 0.25
@export var shake_hz: float = 12.0  # 每秒抖几次（关键参数）

signal shaking_finished()

var _origin_pos: Vector2
var _shaking := false
var _rng := RandomNumberGenerator.new()

func _ready() -> void:
	if not shaking_target:
		shaking_target = self
	_rng.randomize()

func shaking() -> void:
	if _shaking:
		return

	if not shaking_target:
		shaking_target = self

	_origin_pos = shaking_target.position
	_shaking = true

	var end_timer := get_tree().create_timer(shake_duration)
	var interval : float = 1.0 / max(shake_hz, 1.0)
	var next_update := 0.0
	var current_offset := Vector2.ZERO

	while end_timer.time_left > 0.0:
		next_update -= get_process_delta_time()

		if next_update <= 0.0:
			current_offset = Vector2(
				randf_range(-shake_strength, shake_strength),
				randf_range(-shake_strength, shake_strength)
			)
			next_update = interval

		shaking_target.position = _origin_pos + current_offset
		await get_tree().process_frame

	shaking_target.position = _origin_pos
	_shaking = false
	shaking_finished.emit()
