如何选择将表与数字进行比较的最接近值?

时间:2014-04-17 15:51:27

标签: lua logic

基本上我有这个功能,它会移动一个项目,平铺到平铺,直到它到达某个位置

但此项目一次只能移动1个图块

for i= -1, 1 , 2 do -- getting surrounding tiles

           Surrounding_tiles.x = original_pos.x+(i)
           Surrounding_tiles.y = original_pos.y+(i)
-- checking which surrounding tiles are not obstructed

 if Map.IsTileWalkable(Surrounding_tiles.x,Surrounding_tiles.y,original_pos.z)

        then 
-- moving to tile
        Map.MoveItem(xfrom, yfrom, xto, yto,)
 end
end

这里只是一个问题,在选择了没有遮挡的瓷砖之后,我需要它来选择最接近我希望它去的最终位置的一个瓷砖(x和y)

final_position.x
final_position.y

“地图”是一个没有负值的简单网格

如果这太复杂并且需要进行寻路功能,那么就不要错过^^

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案:

local final_position
-- set final position to something

-- Define a distance function that takes a grid position
-- and returns the distance to the final position
local distance = function(start)
    return math.abs(start.x - final_position.x) + math.abs(start.y - final_position.y)
end

-- Define a comparator that compares locations based on
-- distance to final position
local comparator = function(a, b)
    return distance(a) < distance(b)
end

local adj_tiles
-- Set adj_tiles to an array of grid positions

table.sort(adj, comparator) -- Sort adjacent tiles based on distance

local nearest = adj[1] -- Closest is now the first item in the array