Advertisement
ChilliVonWilly

State-Machine-Script

Oct 21st, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class_name PlayerStateMachine extends Node
  2.  
  3. var states: Array[ State ]
  4. var prev_state: State
  5. var current_state: State
  6.  
  7. # Called when the node enters the scene tree for the first time.
  8. func _ready():
  9.     process_mode = Node.PROCESS_MODE_DISABLED
  10.     pass # Replace with function body.
  11.  
  12.  
  13. # Called every frame. 'delta' is the elapsed time since the previous frame.
  14. func _process(delta):
  15.     ChangeState(current_state.Process(delta))
  16.     pass
  17.  
  18.  
  19. func _physics_process(delta):
  20.     ChangeState(current_state.Physics(delta))
  21.     pass
  22.  
  23.  
  24. func _unhandled_input(event):
  25.     ChangeState(current_state.HandleInput(event))
  26.     pass
  27.  
  28.  
  29. func Initialize(_player: Player) -> void:
  30.     states = []
  31.    
  32.     for c in get_children():
  33.         if c is State:
  34.             states.append(c)
  35.        
  36.     if states.size() > 0:
  37.         states[0].player = _player
  38.         ChangeState(states[0])
  39.         process_mode = Node.PROCESS_MODE_INHERIT
  40.  
  41.  
  42. func ChangeState(new_state : State) -> void:
  43.     if new_state == null || new_state == current_state:
  44.         return
  45.    
  46.     if current_state:
  47.         current_state.Exit()
  48.    
  49.     prev_state = current_state
  50.     current_state = new_state
  51.     current_state.Enter()
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement