enemy.gd 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. class_name Enemy extends RigidBody2D
  2. const WALK_SPEED = 50
  3. enum State {
  4. WALKING,
  5. DYING,
  6. }
  7. var _state := State.WALKING
  8. var direction := -1
  9. var anim := ""
  10. var Bullet := preload("res://player/bullet.gd")
  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()