movement_speed.script 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. go.property("acceleration", 100)
  2. go.property("deceleration", 200)
  3. go.property("max_speed", 400)
  4. function init(self)
  5. -- make sure the script will receive user input
  6. msg.post(".", "acquire_input_focus")
  7. -- movement input
  8. self.input = vmath.vector3()
  9. -- the current direction of movement
  10. self.direction = vmath.vector3()
  11. -- the current speed (pixels/second)
  12. self.speed = 0
  13. end
  14. function update(self, dt)
  15. -- is any key pressed?
  16. if self.input.x ~= 0 or self.input.y ~= 0 then
  17. -- set direction of travel from input
  18. self.direction = self.input
  19. -- increase speed
  20. self.speed = self.speed + self.acceleration * dt
  21. -- cap speed
  22. self.speed = math.min(self.speed, self.max_speed)
  23. else
  24. -- decrease speed when no key is pressed
  25. self.speed = self.speed - self.deceleration * dt
  26. self.speed = math.max(self.speed, 0)
  27. end
  28. -- move the game object
  29. local p = go.get_position()
  30. p = p + self.direction * self.speed * dt
  31. go.set_position(p)
  32. -- reset input
  33. self.input = vmath.vector3()
  34. end
  35. function on_input(self, action_id, action)
  36. -- update direction of movement based on currently pressed keys
  37. if action_id == hash("key_up") then
  38. self.input.y = 1
  39. elseif action_id == hash("key_down") then
  40. self.input.y = -1
  41. elseif action_id == hash("key_left") then
  42. self.input.x = -1
  43. elseif action_id == hash("key_right") then
  44. self.input.x = 1
  45. end
  46. end