Advertisement
chris33556

state_machine_1

Oct 17th, 2022
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. extends KinematicBody
  2.  
  3. onready var Anim = $AnimatedSprite3D
  4. var velocity = Vector3()
  5. var is_walk = false
  6. var current_state := 0
  7. enum {WALK, ATTACK, IDLE}
  8.  
  9. var enter_state := true
  10.  
  11. func _physics_process(delta):
  12. match current_state:
  13. WALK:
  14. _walk_state(delta)
  15. ATTACK:
  16. _attack_state(delta)
  17. IDLE:
  18. _idle_state(delta)
  19.  
  20. # state functions
  21.  
  22. func _walk_state(_delta):
  23. Anim.play("walk")
  24. _move()
  25.  
  26. _move_and_slide()
  27. _set_state(_check_walk_state())
  28.  
  29. func _attack_state(_delta):
  30. Anim.play("punch")
  31. velocity.x = 0
  32. _move_and_slide()
  33.  
  34. func _idle_state(_delta):
  35. Anim.play("idle")
  36. velocity.x = 0
  37. _move_and_slide()
  38. _set_state(_check_idle_state())
  39.  
  40. # check functions
  41.  
  42. func _check_idle_state():
  43. var new_state = current_state
  44. if Input.is_action_pressed("move_left") or Input.is_action_pressed("move_right"):
  45. new_state = WALK
  46. elif Input.is_action_just_pressed("punch"):
  47. new_state = ATTACK
  48. return new_state
  49.  
  50. func _check_walk_state():
  51. var new_state = current_state
  52. if Input.is_action_pressed("move_left") or Input.is_action_pressed("move_right"):
  53. new_state = WALK
  54. elif Input.is_action_just_pressed("punch"):
  55. new_state = ATTACK
  56. return new_state
  57.  
  58. # helpers
  59.  
  60. func _move_and_slide():
  61. velocity = move_and_slide(velocity, Vector3.UP)
  62.  
  63. func _move():
  64. if Input.is_action_pressed("move_left"):
  65. velocity.x = -100
  66. $AnimatedSprite3D.flip_h = true
  67. elif Input.is_action_pressed("move_right"):
  68. velocity.x = 100
  69. $AnimatedSprite3D.flip_h = false
  70. else:
  71. velocity.x = 0
  72. Anim.play("idle")
  73.  
  74.  
  75. func _set_state(new_state):
  76. if new_state != current_state:
  77. enter_state = true
  78. current_state = new_state
  79.  
  80.  
  81. func _on_AnimatedSprite3D_animation_finished():
  82. var anim_name = $AnimatedSprite3D.animation
  83. if anim_name == "punch":
  84. _set_state(IDLE)
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement