enemy.gd 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class_name Enemy
  2. extends RigidBody2D
  3. const WALK_SPEED = 50
  4. enum State {
  5. WALKING,
  6. DYING,
  7. }
  8. var _state := State.WALKING
  9. var direction := -1
  10. var anim := ""
  11. @onready var rc_left := $RaycastLeft as RayCast2D
  12. @onready var rc_right := $RaycastRight as RayCast2D
  13. func _integrate_forces(state: PhysicsDirectBodyState2D) -> void:
  14. var velocity := state.get_linear_velocity()
  15. var new_anim := anim
  16. if _state == State.DYING:
  17. new_anim = "explode"
  18. elif _state == State.WALKING:
  19. new_anim = "walk"
  20. var wall_side := 0.0
  21. for collider_index in state.get_contact_count():
  22. var collider := state.get_contact_collider_object(collider_index)
  23. var collision_normal := state.get_contact_local_normal(collider_index)
  24. if collider is Bullet and not (collider as Bullet).disabled:
  25. _bullet_collider.call_deferred(collider, state, collision_normal)
  26. break
  27. if collision_normal.x > 0.9:
  28. wall_side = 1.0
  29. elif collision_normal.x < -0.9:
  30. wall_side = -1.0
  31. if wall_side != 0 and wall_side != direction:
  32. direction = -direction
  33. ($Sprite2D as Sprite2D).scale.x = -direction
  34. if direction < 0 and not rc_left.is_colliding() and rc_right.is_colliding():
  35. direction = -direction
  36. ($Sprite2D as Sprite2D).scale.x = -direction
  37. elif direction > 0 and not rc_right.is_colliding() and rc_left.is_colliding():
  38. direction = -direction
  39. ($Sprite2D as Sprite2D).scale.x = -direction
  40. velocity.x = direction * WALK_SPEED
  41. if anim != new_anim:
  42. anim = new_anim
  43. ($AnimationPlayer as AnimationPlayer).play(anim)
  44. state.set_linear_velocity(velocity)
  45. func _die() -> void:
  46. queue_free()
  47. func _pre_explode() -> void:
  48. #make sure nothing collides against this
  49. $Shape1.queue_free()
  50. $Shape2.queue_free()
  51. $Shape3.queue_free()
  52. ($SoundExplode as AudioStreamPlayer2D).play()
  53. func _bullet_collider(
  54. collider: Bullet,
  55. state: PhysicsDirectBodyState2D,
  56. collision_normal: Vector2
  57. ) -> void:
  58. _state = State.DYING
  59. state.set_angular_velocity(signf(collision_normal.x) * 33.0)
  60. physics_material_override.friction = 1
  61. collider.disable()
  62. ($SoundHit as AudioStreamPlayer2D).play()