Advertisement
Guest User

Untitled

a guest
Nov 13th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. """
  2. Base interface for a generic state machine
  3. It handles initializing, setting the machine active or not
  4. delegating _physics_process, _input calls to the State nodes,
  5. and changing the current/active state.
  6. See the PlayerV2 scene for an example on how to use it
  7. """
  8. extends Node
  9.  
  10. signal state_changed(current_state)
  11.  
  12. """
  13. You must set a starting node from the inspector or on
  14. the node that inherits from this state machine interface
  15. If you don't the game will crash (on purpose, so you won't
  16. forget to initialize the state machine)
  17. """
  18. export(NodePath) var START_STATE
  19. var states_map = {}
  20.  
  21. var states_stack = []
  22. var current_state = null
  23. var _active = false setget set_active
  24.  
  25. func _ready():
  26. for child in get_children():
  27. child.connect("finished", self, "_change_state")
  28. initialize(START_STATE)
  29.  
  30. func initialize(start_state):
  31. set_active(true)
  32. states_stack.push_front(get_node(start_state))
  33. current_state = states_stack[0]
  34. current_state.enter()
  35.  
  36. func set_active(value):
  37. _active = value
  38. set_physics_process(value)
  39. set_process_input(value)
  40. if not _active:
  41. states_stack = []
  42. current_state = null
  43.  
  44. func _input(event):
  45. current_state.handle_input(event)
  46.  
  47. func _physics_process(delta):
  48. current_state.update(delta)
  49.  
  50. func _on_animation_finished(anim_name):
  51. if not _active:
  52. return
  53. current_state._on_animation_finished(anim_name)
  54.  
  55. func _change_state(state_name):
  56. if not _active:
  57. return
  58. current_state.exit()
  59.  
  60. if state_name == "previous":
  61. states_stack.pop_front()
  62. else:
  63. states_stack[0] = states_map[state_name]
  64.  
  65. current_state = states_stack[0]
  66. emit_signal("state_changed", current_state)
  67.  
  68. if state_name != "previous":
  69. current_state.enter()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement