2014-04-17 115 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