apply_force.script 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. -- Multiplier applied to the touch->block direction vector.
  2. local force_factor = 30
  3. -- Debug line color used by @render:draw_line.
  4. local debug_line_color = vmath.vector4(0, 0.5, 1, 1)
  5. -- Game object ids of dynamic blocks controlled by this script.
  6. -- The script is attached to the "controller" object in the collection.
  7. local blocks = {
  8. [1] = "block1",
  9. [2] = "block2",
  10. [3] = "block3",
  11. [4] = "block4",
  12. }
  13. function init(self)
  14. -- <1> Receive touch/mouse input in on_input().
  15. msg.post(".", "acquire_input_focus")
  16. end
  17. -- Pre-hashed action id for the touch action.
  18. local touch_action_id = hash("touch")
  19. function on_input(self, action_id, action)
  20. -- <2> Built-in "touch" also maps mouse clicks on desktop.
  21. if action_id == touch_action_id then
  22. -- <3> Iterate over all blocks and apply force to each.
  23. for _, block in pairs(blocks) do
  24. -- <4> Compute the force vector by subtracting the block center from the touch position.
  25. local center = go.get_world_position(block)
  26. local touch = vmath.vector3(action.x, action.y, center.z)
  27. local force = (touch - center) * force_factor
  28. -- <5> Send force to the block's dynamic collision object.
  29. msg.post(block, "apply_force", {
  30. force = force,
  31. position = center
  32. })
  33. -- <6> Visualize direction from touch point to block center.
  34. msg.post("@render:", "draw_line", {
  35. start_point = touch,
  36. end_point = center,
  37. color = debug_line_color
  38. })
  39. end
  40. end
  41. end
  42. function final(self)
  43. -- Stop receiving input when the controller is destroyed.
  44. msg.post(".", "release_input_focus")
  45. end