Reputation: 3151
Basically i have this function that will move an item, tile to tile until it reaches a certain position
but this item can only be moved 1 tile at a time
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
there's just a problem here, after selecting the not obstructed tiles, i need it to select the one tile(x and y) that is closest to the final position i want it to go
final_position.x
final_position.y
The "map" is a simple grid with no negative values
if this is too complicated and would require to make a pathfinding function then nevermind^^
Upvotes: 1
Views: 539
Reputation: 26549
A simple solution:
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
Upvotes: 1