extends LimboState

@export var run_dust_distance:= 50

var _accelerated_distance: float
var _is_first_update: bool
var _last_frame_position: Vector2

var _run_dust_counter: float

func _enter() -> void:
	_reset_distance()
	_reset_run_dust_counter()
	_is_first_update = true
	return

func _exit() -> void:
	_reset_distance()

func _update(delta: float) -> void:
	_handle_move_input()
	
	## 更新並獲取到delta ditance
	var delta_distance = _update_accelerated_distance() as float
	
	#print(delta_distance)
	
	## 如果移動了一定的距離，則播放dust特效
	_run_dust_counter -= delta_distance
	if _run_dust_counter < 0:
		agent.on_run_dust()
		_reset_run_dust_counter()

func _handle_move_input() -> void:
	var move_direction = agent.get_move_input().x as float
	if move_direction == 0.0:
		get_root().dispatch(self.EVENT_FINISHED)
		agent.locomotion_comp.stop_movement(0.0) #用0唤起制动加速度
		return
	agent.locomotion_comp.add_movement_input(move_direction)

##更新距離，返回的是Delta Distance
func _update_accelerated_distance() -> float:
	var c = agent.global_position as Vector2
	
	if _is_first_update:
		_last_frame_position = c
		_accelerated_distance = 0
		_is_first_update = false
		return _accelerated_distance
	
	var _delta = c.distance_to(_last_frame_position) as float
	_last_frame_position = c
	_accelerated_distance += _delta
	
	return _delta

func _reset_distance() -> void:
	_accelerated_distance = 0
	_last_frame_position = Vector2.ZERO

func _reset_run_dust_counter() -> void:
	_run_dust_counter = run_dust_distance
