Advertisement
Guest User

Vanilla closestLocationInRange function

a guest
Aug 23rd, 2021
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. function closestLocationInRange(position, parent, range, exclude)
  2. local locations = util.map(celestial.children(parent), function(p) return {"coordinate", p} end)
  3. local objectPositions = {}
  4. local objectOrbits = {}
  5.  
  6. if compare(celestial.currentSystem(), coordinateSystem(parent)) then
  7. -- current system, use all current objects even temporary
  8. for _,uuid in pairs(celestial.systemObjects()) do
  9. local orbit = celestial.objectOrbit(uuid)
  10. if orbit then
  11. objectPositions[uuid] = celestial.orbitPosition(orbit)
  12. else
  13. objectPositions[uuid] = celestial.objectPosition(uuid)
  14. end
  15. table.insert(locations, {"object", uuid})
  16. end
  17. elseif parent.planet == 0 then
  18. -- another system, use permanent mapped objects
  19. for uuid,object in pairs(player.mappedObjects(parent)) do
  20. if celestial.objectTypeConfig(object.typeName).permanent then
  21. if object.orbit then
  22. objectPositions[uuid] = celestial.orbitPosition(object.orbit)
  23. table.insert(locations, {"object", uuid})
  24. end
  25. end
  26. end
  27. end
  28. -- include parent if it's a planet
  29. if parent.planet > 0 then
  30. table.insert(locations, {"coordinate", parent})
  31. end
  32.  
  33. locations = util.filter(locations, function(location)
  34. if location[1] == "coordinate" then
  35. local parameters = celestial.planetParameters(location[2])
  36. if parameters and parameters.worldType == "Asteroids" then
  37. return false
  38. end
  39. end
  40. return true
  41. end)
  42.  
  43. local distance = function(location, first)
  44. local second
  45. if location[1] == "coordinate" then
  46. second = celestial.planetPosition(location[2])
  47. elseif location[1] == "object" then
  48. second = objectPositions[location[2]]
  49. end
  50.  
  51. return vec2.mag(vec2.sub(first, second))
  52. end
  53. locations = util.filter(locations, function(s)
  54. return distance(s, position) < range and not compare(s, exclude)
  55. end)
  56. table.sort(locations, function(a, b)
  57. return distance(a, position) < distance(b, position)
  58. end)
  59. return locations[1]
  60. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement