bee.script 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. -- function to convert screen (mouse/touch) coordinates to
  2. -- world coordinates given a camera component
  3. -- this function will use the camera view and projection to
  4. -- translate the screen coordinates into world coordinates
  5. local function screen_to_world(x, y, z, camera_id)
  6. local projection = camera.get_projection(camera_id)
  7. local view = camera.get_view(camera_id)
  8. local w, h = window.get_size()
  9. -- https://defold.com/manuals/camera/#converting-mouse-to-world-coordinates
  10. local inv = vmath.inv(projection * view)
  11. x = (2 * x / w) - 1
  12. y = (2 * y / h) - 1
  13. z = (2 * z) - 1
  14. local x1 = x * inv.m00 + y * inv.m01 + z * inv.m02 + inv.m03
  15. local y1 = x * inv.m10 + y * inv.m11 + z * inv.m12 + inv.m13
  16. local z1 = x * inv.m20 + y * inv.m21 + z * inv.m22 + inv.m23
  17. return x1, y1, z1
  18. end
  19. function init(self)
  20. -- send input events to this script
  21. msg.post(".", "acquire_input_focus")
  22. end
  23. function on_input(self, action_id, action)
  24. if action_id == hash("touch") and action.pressed then
  25. -- convert mouse/touch screen position to world position
  26. local worldx, worldy = screen_to_world(action.screen_x, action.screen_y, 0, "#camera")
  27. local world = vmath.vector3(worldx, worldy, 0)
  28. go.animate(".", "position", go.PLAYBACK_ONCE_FORWARD, world, go.EASING_LINEAR, 0.5, 0)
  29. end
  30. end