raycast.script 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. local function draw_line(from, to)
  2. msg.post("@render:", "draw_line", { start_point = from, end_point = to, color = vmath.vector4(1,0,0,1) })
  3. end
  4. function init(self)
  5. msg.post(".", "acquire_input_focus") -- <1>
  6. self.to = vmath.vector3() -- <2>
  7. end
  8. function update(self, dt)
  9. local from = go.get_position()
  10. local to = self.to
  11. local result = physics.raycast(from, to, { hash("stone") }) -- <4>
  12. if result then
  13. draw_line(from, result.position) -- <5>
  14. else
  15. draw_line(from, to) -- <6>
  16. end
  17. end
  18. function on_input(self, action_id, action)
  19. if not action_id or action_id == hash("touch") then -- <3>
  20. self.to.x = action.x
  21. self.to.y = action.y
  22. end
  23. end
  24. --[[
  25. 1. Tell the engine that this object ("." is shorthand for the current game object) should listen to input. Any input will be received in the `on_input()` function.
  26. 2. Store a position vector `to` in `self` (the current script component) to keep track of where to do a raycast.
  27. 3. If we receive input (touch or mouse movement) we update the position to where we should cast the ray.
  28. 4. Perform a raycast from the current game object position to where the mouse/touch is. The raycast is configured to only hit collision objects belonging to the `stone` group. The result will be stored in `result` or `nil` if no hit.
  29. 5. The raycast hit something! Draw a line (using the helper function at the top of the script) from the current game object position to where the raycast hit.
  30. 6. The raycast missed! Draw a line (using the helper function at the top of the script) from the current game object position to where the mouse/touch was.
  31. --]]