Advertisement
otorp2

statemachine

Dec 22nd, 2016
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. extends Node2D
  2.  
  3. var states = {}
  4.  
  5. var state # current state
  6.  
  7. func _ready():
  8. states["one"] = StateOne.new()
  9. states["two"] = StateTwo.new()
  10.  
  11. for s in states:
  12. states[s].connect("change_state_plz", self, "change_state")
  13.  
  14. # set the initial state
  15. state = states["one"]
  16. set_process(true)
  17.  
  18. func _process(delta):
  19. state._process(delta)
  20.  
  21. func change_state(next_state):
  22. state = states[next_state]
  23. # maybe call a `unload` and `load` function on the states to show them that they are active now
  24.  
  25. class StateOne:
  26. signal change_state_plz(next_state)
  27. func _process(delta):
  28. print("DD")
  29. pass
  30. class StateTwo:
  31. signal change_state_plz(next_state)
  32. func _process(delta):
  33. print("qq")
  34. pass
  35.  
  36.  
  37.  
  38. Not tested
  39. but that's how I'd do it
  40. You can then do emit_signal("name of next state")anywhere in a state to switch to a different state
  41. since you can swap out state the call state._process(delta) will always call the function in the currently active state
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement