pointer.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. local pointer = {}
  2. pointer.__index = pointer
  3. local unpack = unpack or table.unpack
  4. function pointer.new(options)
  5. local self = setmetatable({}, pointer)
  6. self:init(options)
  7. return self
  8. end
  9. function pointer:init(options)
  10. self.source = options and options.source
  11. self.range = options and options.range or 10
  12. self.world = options and options.world
  13. self.path = nil
  14. self.hit = nil
  15. end
  16. function pointer:update()
  17. if not self.source then return end
  18. local r = self.range
  19. local x, y, z = self.source:getPosition()
  20. local dx, dy, dz = quat(self.source:getOrientation()):direction():unpack()
  21. local tx, ty, tz = x + dx * r, y + dy * r, z + dz * r
  22. if self.world then
  23. local closest = math.huge
  24. self.hit = nil
  25. self.world:raycast(x, y, z, tx, ty, tz, function(shape, hx, hy, hz, nx, ny, nz)
  26. local distance = (x - hx) ^ 2 + (y - hy) ^ 2 + (z - hz) ^ 2
  27. if distance < closest then
  28. closest = distance
  29. tx, ty, tz = hx, hy, hz
  30. self.hit = { x = hx, y = hy, z = hz, nx = nx, ny = ny, nz = nz, collider = shape:getCollider() }
  31. end
  32. end)
  33. else
  34. local length = -y / dy
  35. if length > 0 and length <= r then
  36. tx, ty, tz = x + dx * length, y + dy * length, z + dz * length
  37. self.hit = { x = tx, y = ty, z = tz, nx = 0, ny = 1, nz = 0 }
  38. else
  39. self.hit = nil
  40. end
  41. end
  42. self.path = { x, y, z, tx, ty, tz }
  43. return self.hit
  44. end
  45. function pointer:getPath()
  46. return self.path
  47. end
  48. function pointer:getHit()
  49. return self.hit
  50. end
  51. function pointer:getSource()
  52. return self.source
  53. end
  54. function pointer:setSource(source)
  55. assert(source.getPosition and source.getOrientation, 'Pointer source needs getPosition and getOrientation functions')
  56. self.source = source
  57. end
  58. return pointer