move_forward.script 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. go.property("acceleration", 100)
  2. go.property("deceleration", 200)
  3. go.property("max_speed", 400)
  4. go.property("rotation_speed", 180)
  5. -- unit vector pointing up
  6. local UP = vmath.vector3(0, 1, 0)
  7. function init(self)
  8. -- make sure the script will receive user input
  9. msg.post(".", "acquire_input_focus")
  10. -- movement input
  11. self.input = vmath.vector3()
  12. -- the current speed (pixels/second)
  13. self.speed = 0
  14. end
  15. function update(self, dt)
  16. -- accelerating?
  17. if self.input.y > 0 then
  18. -- increase speed
  19. self.speed = self.speed + self.acceleration * dt
  20. -- cap speed
  21. self.speed = math.min(self.speed, self.max_speed)
  22. else
  23. -- decrease speed when not accelerating
  24. self.speed = self.speed - self.deceleration * dt
  25. self.speed = math.max(self.speed, 0)
  26. end
  27. -- apply rotation based on self.input.x (left/right)
  28. local rot = go.get_rotation()
  29. -- amount to rotate (in radians)
  30. local rot_amount = math.rad(self.rotation_speed * self.input.x * dt)
  31. -- apply rotation as a quaternion created from a rotation of 'rot_amount' degrees around the z-axis
  32. rot = rot * vmath.quat_rotation_z(rot_amount)
  33. go.set_rotation(rot)
  34. -- move the game object
  35. local p = go.get_position()
  36. -- amount to move (pixels)
  37. local move_amount = UP * self.speed * dt
  38. -- apply rotation to movement vector to move game object in the direction of rotation
  39. p = p + vmath.rotate(rot, move_amount)
  40. go.set_position(p)
  41. -- reset input
  42. self.input = vmath.vector3()
  43. end
  44. function on_input(self, action_id, action)
  45. -- update direction of movement based on currently pressed keys
  46. if action_id == hash("key_up") then
  47. self.input.y = 1
  48. elseif action_id == hash("key_down") then
  49. self.input.y = -1
  50. elseif action_id == hash("key_left") then
  51. self.input.x = 1
  52. elseif action_id == hash("key_right") then
  53. self.input.x = -1
  54. end
  55. end