enemy.script 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. -- Define different properties of the script:
  2. go.property("sprite", hash("ufoGreen"))
  3. go.property("health_points", 1)
  4. go.property("speed", vmath.vector3(100, 100, 0))
  5. go.property("is_random", true)
  6. function init(self)
  7. -- Set animation of the sprite to the one defined by its property self.sprite:
  8. sprite.play_flipbook("#sprite", self.sprite)
  9. -- Add randomness to horizontal direction - this way enemy horizontal speed may be inverted or cleared:
  10. -- -1 * self.speed.x - inverted direction
  11. -- 0 * self.speed.x - cleared direction
  12. -- 1 * self.speed.x - regular direction
  13. self.speed.x = math.random(-1, 1) * self.speed.x
  14. -- If self.is_random boolean property is true:
  15. if self.is_random then
  16. -- add a timer to randomly switch horizontal speed every second:
  17. timer.delay(1, true, function()
  18. self.speed.x = math.random(-1, 1) * self.speed.x
  19. end)
  20. end
  21. end
  22. function update(self, dt)
  23. -- Update enemy position based on its current speed:
  24. local pos = go.get_position()
  25. pos = pos + self.speed * dt
  26. go.set_position(pos)
  27. -- Bounce enemy off "walls":
  28. if pos.x > 600 or pos.x < 50 then
  29. self.speed.x = -self.speed.x
  30. end
  31. -- Remove enemy if it goes out of screen:
  32. if pos.y < -50 then
  33. go.delete()
  34. end
  35. end
  36. function on_message(self, message_id, message, sender)
  37. -- React to collision with bullet:
  38. if message_id == hash("trigger_response") and message.enter then
  39. -- Remove one health point
  40. self.health_points = self.health_points - 1
  41. -- Play particlefx for damage taken:
  42. particlefx.play("#boom")
  43. -- When no health points left - remove this ship
  44. if self.health_points <= 0 then
  45. go.delete()
  46. end
  47. end
  48. end