Add api function to find nearest area

This commit is contained in:
Ciaran Gultnieks 2014-03-22 10:38:45 +00:00
parent 4bffabfa60
commit c523b44190

42
api.lua
View File

@ -1,4 +1,46 @@
-- Temporary compatibility function - see minetest PR#1180
if not vector.interpolate then
vector.interpolate = function(pos1, pos2)
return {x = pos1.x + (pos2.x - pos1.x) * factor,
y = pos1.y + (pos2.y - pos1.y) * factor,
z = pos1.z + (pos2.z - pos1.z) * factor}
end
end
-- Returns the nearest area to the given position, optionally checking only
-- areas matching a given pattern (which is a lua regex). The pattern will
-- be amended to make it case-insensitive.
-- Returns nil if nothing could be found, otherwise the area and the
-- distance to it.
-- maxdist is the maximum distance at which to search.
function areas:findNearestArea(pos, pattern, maxdist)
local nearest, nearestdist
if pattern then
-- Make the pattern case-insensitive...
pattern = pattern:gsub("(%%?)(.)", function(percent, letter)
if percent ~= "" or not letter:match("%a") then
return percent .. letter
else
return string.format("[%s%s]", letter:lower(), letter:upper())
end
end)
end
for id, area in pairs(self.areas) do
if (not pattern) or string.find(area.name, pattern) then
local centre = vector.interpolate(area.pos1, area.pos2, 0.5)
local dist = vector.distance(pos, centre)
if ((not nearestdist) or dist < nearestdist) and ((not maxdist) or dist <= maxdist) then
nearest = area
nearestdist = dist
end
end
end
return nearest, nearestdist
end
-- Returns a list of areas that include the provided position -- Returns a list of areas that include the provided position
function areas:getAreasAtPos(pos) function areas:getAreasAtPos(pos)
local a = {} local a = {}