move.script 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. function init(self)
  2. msg.post(".", "acquire_input_focus") -- <1>
  3. self.vel = vmath.vector3() -- <2>
  4. end
  5. function update(self, dt)
  6. local pos = go.get_position() -- <3>
  7. pos = pos + self.vel * dt -- <4>
  8. go.set_position(pos) -- <5>
  9. self.vel.x = 0 -- <6>
  10. self.vel.y = 0
  11. end
  12. function on_input(self, action_id, action)
  13. if action_id == hash("up") then
  14. self.vel.y = 150 -- <7>
  15. elseif action_id == hash("down") then
  16. self.vel.y = -150
  17. elseif action_id == hash("left") then
  18. self.vel.x = -150 -- <8>
  19. elseif action_id == hash("right") then
  20. self.vel.x = 150
  21. end
  22. end
  23. --[[
  24. 1. Tell the engine that the current game object ("." is
  25. shorthand for that) should receive user input to the function
  26. `on_input()` in its script components.
  27. 2. Construct a vector to indicate velocity. It will initially be
  28. zero.
  29. 3. Each frame, get the current position and store in `pos`.
  30. 4. Add the velocity, scaled to the current frame length. Velocity
  31. is therefore expressed in pixels per second.
  32. 5. Set the game object's position to the newly calculated position.
  33. 6. Zero out the velocity. If no input is given, there should be
  34. no movement.
  35. 7. If the user presses "up", set the y component of the velocity to 150.
  36. If the user presses "down", set the y component to -150.
  37. 8. Similarly, if the user presses "left", set the x component of the velocity to -150.
  38. And finally, if the user presses "right", set the x component to 150.
  39. --]]