Tales-of-PKMN/game/player/states/state_machine.gd
2026-10-13 09:21:01 +02:00

92 lines
2.7 KiB
GDScript

extends Node
class_name StateMachine
@export var initial_state : State
@export var throw_action : StringName = &"player_throw"
const THROW_ENTRY_STATES : Array[String] = ["Idle", "Walk", "Run", "Crouch"] #etats depuis lesquels RT lance sans viser
var curr_state : State
var curr_state_name : String
var states : Dictionary = {}
var blocked_states : Dictionary = {} #noms (en minuscules) des etats dont l'entree est refusee
@onready var char_ref : CharacterBody3D = $".."
func _ready() -> void:
#get all the state childrens
for child in get_children():
if child is State:
states[child.name.to_lower()] = child
child.transitioned.connect(on_state_child_transition)
child.hints_changed.connect(_on_hints_changed.bind(child))
#if initial state, transition to it
if initial_state:
await get_tree().create_timer(0.1).timeout
initial_state.enter(char_ref)
curr_state = initial_state
curr_state_name = curr_state.state_name
publish_hints()
func _process(delta : float) -> void:
if curr_state: curr_state.update(delta)
func _physics_process(delta: float) -> void:
if curr_state:
if try_start_throw(): return
curr_state.physics_update(delta)
func try_start_throw() -> bool:
if !(curr_state_name in THROW_ENTRY_STATES): return false
if !Input.is_action_just_pressed(throw_action): return false
if !char_ref.is_on_floor(): return false
var selected : PokemonInstance = GameData.get_selected_pokemon()
if selected == null: return false
#pokemon deja dehors : l'appui le rappelle au lieu de lancer
var already_out : SentPokemon = SentPokemon.find_for(get_tree(), selected)
if already_out:
already_out.recall()
return false
if !states.has("throwstate"): return false
on_state_child_transition(curr_state, "ThrowState")
return true
func on_state_child_transition(state : State, new_state_name : String) -> void:
#manage the transition from one state to another
if state != curr_state: return
var new_state = states.get(new_state_name.to_lower())
if !new_state: return
if blocked_states.has(new_state_name.to_lower()): return
#exit the current state
if curr_state: curr_state.exit()
#enter the new state
new_state.enter(char_ref)
curr_state = new_state
curr_state_name = curr_state.state_name
publish_hints()
func set_state_blocked(state_name : String, blocked : bool) -> void:
if blocked: blocked_states[state_name.to_lower()] = true
else: blocked_states.erase(state_name.to_lower())
func _on_hints_changed(state : State) -> void:
if state == curr_state: publish_hints()
func publish_hints() -> void:
if !curr_state: return
var actions = curr_state.get_hints()
if actions != null: Hints.set_state_hints(actions) #null = on garde les hints précédents (si tu as gardé cette option pour Dodge)