target.lua 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. Target = class()
  2. local teamFilters = {
  3. all = function() return true end,
  4. enemy = function(a, b) return a.team ~= b.team end,
  5. ally = function(a, b) return a.team == b.team end
  6. }
  7. local getEntries = {
  8. shrine = function(source, teamFilter, t)
  9. ctx.shrines:each(function(shrine)
  10. if source ~= shrine and not shrine.untargetable and teamFilter(source, shrine) then
  11. table.insert(t, {shrine, math.abs(shrine.x - source.x)})
  12. end
  13. end)
  14. end,
  15. player = function(source, teamFilter, t)
  16. ctx.players:each(function(player)
  17. if source ~= player and not player.untargetable and not player.dead and player.invincible == 0 and teamFilter(source, player) then
  18. table.insert(t, {player, math.abs(player.x - source.x)})
  19. end
  20. end)
  21. end,
  22. unit = function(source, teamFilter, t)
  23. ctx.units:each(function(unit)
  24. if source ~= unit and not unit.untargetable and not unit.dying and teamFilter(source, unit) then
  25. table.insert(t, {unit, math.abs(unit.x - source.x)})
  26. end
  27. end)
  28. end
  29. }
  30. local function halp(source, teamFilter, arg)
  31. local targets = {}
  32. teamFilter = teamFilters[teamFilter]
  33. table.each(arg, function(kind) getEntries[kind](source, teamFilter, targets) end)
  34. return targets
  35. end
  36. function Target:closest(source, teamFilter, ...)
  37. local targets = halp(source, teamFilter, {...})
  38. table.sort(targets, function(a, b) return a[2] < b[2] end)
  39. if targets[1] then return unpack(targets[1]) end
  40. return nil
  41. end
  42. function Target:inRange(source, range, teamFilter, ...)
  43. local targets = halp(source, teamFilter, {...})
  44. local i = 1
  45. while i <= #targets do
  46. if targets[i][2] > range + targets[i][1].width / 2 then table.remove(targets, i)
  47. else i = i + 1 end
  48. end
  49. table.sort(targets, function(a, b) return a[2] < b[2] end)
  50. return table.map(targets, function(t) return t[1] end)
  51. end
  52. function Target:location(source, range)
  53. local ground = ctx.map.height - ctx.map.groundHeight
  54. local mx = ctx.view:worldPoint(love.mouse.getX())
  55. local x = math.clamp(mx, source.x - range, source.x + range)
  56. return x, ground
  57. end
  58. function Target:atMouse(...)
  59. local mx, my = ctx.view:worldPoint(love.mouse.getPosition())
  60. for _, entry in ipairs(self:inRange(...)) do
  61. if entry:contains(mx, my) then return entry end
  62. end
  63. return nil
  64. end