Chicken.gd 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. class_name Chicken
  2. extends KinematicBody2D
  3. enum State {IDLE, WALKING, ANGRY, RUNNING}
  4. export var walk_linear_speed = 100
  5. export var run_boost = 4
  6. export var push_impulse = 150
  7. var velocity = Vector2.ZERO
  8. var _current_state = State.IDLE
  9. func attack(from: Vector2, angle: float):
  10. position = from
  11. velocity = Vector2(walk_linear_speed, 0).rotated(angle)
  12. $AnimatedSprite.play("walk")
  13. _update_sprite_direction()
  14. _current_state = State.WALKING
  15. func _physics_process(delta: float):
  16. var collision = _move(delta)
  17. _collide_and_react(collision)
  18. func _on_VisibilityNotifier2D_screen_exited():
  19. _die()
  20. func _on_Spawner_reset():
  21. _die()
  22. func _on_AngryTimer_timeout():
  23. assert(_current_state == State.ANGRY)
  24. _start_running()
  25. func _die():
  26. queue_free()
  27. func _move(delta: float) -> KinematicCollision2D:
  28. if _current_state == State.WALKING or _current_state == State.RUNNING:
  29. return move_and_collide(velocity * delta, false)
  30. else:
  31. return move_and_collide(Vector2.ZERO, false)
  32. func _collide_and_react(collision: KinematicCollision2D) -> void:
  33. if collision == null:
  34. return
  35. var collider = collision.get_collider()
  36. if collider is Node2D:
  37. var node_collider = collider as Node
  38. if _current_state == State.WALKING:
  39. if node_collider.is_in_group("chicken") and _facing_collider(collision.get_normal()):
  40. _turn_away()
  41. elif node_collider.is_in_group("wheel"):
  42. _get_angry()
  43. if collider is RigidBody2D:
  44. _push_away(collider as RigidBody2D, -collision.normal)
  45. func _turn_away() -> void:
  46. velocity.x = -velocity.x
  47. _update_sprite_direction()
  48. func _push_away(body: RigidBody2D, dir: Vector2) -> void:
  49. body.apply_central_impulse(dir * push_impulse)
  50. func _get_angry() -> void:
  51. $AngryTimer.start()
  52. $AnimatedSprite.play("get_hit")
  53. _current_state = State.ANGRY
  54. func _start_running() -> void:
  55. velocity *= run_boost
  56. $AnimatedSprite.play("run")
  57. _current_state = State.RUNNING
  58. func _facing_collider(normal: Vector2) -> bool:
  59. return normal.x * velocity.normalized().x < -0.5
  60. func _update_sprite_direction() -> void:
  61. $AnimatedSprite.flip_h = velocity.x < 0.0