enemy.gd 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. class_name Enemy extends CharacterBody2D
  2. enum State {
  3. WALKING,
  4. DEAD,
  5. }
  6. const WALK_SPEED = 22.0
  7. var _state := State.WALKING
  8. @onready var gravity: int = ProjectSettings.get("physics/2d/default_gravity")
  9. @onready var platform_detector := $PlatformDetector as RayCast2D
  10. @onready var floor_detector_left := $FloorDetectorLeft as RayCast2D
  11. @onready var floor_detector_right := $FloorDetectorRight as RayCast2D
  12. @onready var sprite := $Sprite2D as Sprite2D
  13. @onready var animation_player := $AnimationPlayer as AnimationPlayer
  14. func _physics_process(delta: float) -> void:
  15. if _state == State.WALKING and velocity.is_zero_approx():
  16. velocity.x = WALK_SPEED
  17. velocity.y += gravity * delta
  18. if not floor_detector_left.is_colliding():
  19. velocity.x = WALK_SPEED
  20. elif not floor_detector_right.is_colliding():
  21. velocity.x = -WALK_SPEED
  22. if is_on_wall():
  23. velocity.x = -velocity.x
  24. move_and_slide()
  25. if velocity.x > 0.0:
  26. sprite.scale.x = 0.8
  27. elif velocity.x < 0.0:
  28. sprite.scale.x = -0.8
  29. var animation := get_new_animation()
  30. if animation != animation_player.current_animation:
  31. animation_player.play(animation)
  32. func destroy() -> void:
  33. _state = State.DEAD
  34. velocity = Vector2.ZERO
  35. func get_new_animation() -> StringName:
  36. var animation_new: StringName
  37. if _state == State.WALKING:
  38. if velocity.x == 0:
  39. animation_new = &"idle"
  40. else:
  41. animation_new = &"walk"
  42. else:
  43. animation_new = &"destroy"
  44. return animation_new