enemy.gd 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. var Bullet = preload("res://player/bullet.gd")
  12. onready var rc_left = $RaycastLeft
  13. onready var rc_right = $RaycastRight
  14. func _integrate_forces(s):
  15. var lv = s.get_linear_velocity()
  16. var new_anim = anim
  17. if state == State.DYING:
  18. new_anim = "explode"
  19. elif state == State.WALKING:
  20. new_anim = "walk"
  21. var wall_side = 0.0
  22. for i in range(s.get_contact_count()):
  23. var cc = s.get_contact_collider_object(i)
  24. var dp = s.get_contact_local_normal(i)
  25. if cc:
  26. if cc is Bullet and not cc.disabled:
  27. # enqueue call
  28. call_deferred("_bullet_collider", cc, s, dp)
  29. break
  30. if dp.x > 0.9:
  31. wall_side = 1.0
  32. elif dp.x < -0.9:
  33. wall_side = -1.0
  34. if wall_side != 0 and wall_side != direction:
  35. direction = -direction
  36. ($Sprite as Sprite).scale.x = -direction
  37. if direction < 0 and not rc_left.is_colliding() and rc_right.is_colliding():
  38. direction = -direction
  39. ($Sprite as Sprite).scale.x = -direction
  40. elif direction > 0 and not rc_right.is_colliding() and rc_left.is_colliding():
  41. direction = -direction
  42. ($Sprite as Sprite).scale.x = -direction
  43. lv.x = direction * WALK_SPEED
  44. if anim != new_anim:
  45. anim = new_anim
  46. ($AnimationPlayer as AnimationPlayer).play(anim)
  47. s.set_linear_velocity(lv)
  48. func _die():
  49. queue_free()
  50. func _pre_explode():
  51. #make sure nothing collides against this
  52. $Shape1.queue_free()
  53. $Shape2.queue_free()
  54. $Shape3.queue_free()
  55. # Stay there
  56. mode = MODE_STATIC
  57. ($SoundExplode as AudioStreamPlayer2D).play()
  58. func _bullet_collider(cc, s, dp):
  59. mode = MODE_RIGID
  60. state = State.DYING
  61. s.set_angular_velocity(sign(dp.x) * 33.0)
  62. physics_material_override.friction = 1
  63. cc.disable()
  64. ($SoundHit as AudioStreamPlayer2D).play()