2014-04-17 76 views
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 

移动1瓦这里也只是一个问题,选择不受阻碍地砖后,我需要它来选择一个区块(x和y)是最接近最终位置,我想它去

final_position.x 
final_position.y 

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

,如果这是过于复杂,将需要做出寻路功能,那么请不要介意^^

回答

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