- Home /
Tile-based maps & movement - linking tiles?
Hi all
I am working on a tile-based, turn-based game in Unity2D, with random maps. I've gotten to a point where I have a random maps, and the correct unit movement behavior, but my method of moving between tiles is proving cumbersome.
Basically, each tile is a GameObject with a sprite and a script. The script describes the tile (primarily, if it can be walked across- "walkable"), and each tile is linked to it's 8 neighbours in an Array, indexed clockwise from 12 o clock (making 0 up, 2 right, 4 down, 6 left, and odd numbers being diagonal neighbours).
THere is the movement code for my unit, where he checks if he can move into the block, and if he can, he moves:
public bool MoveUp(){
tile destination = currentTile.neighbours[0];
if(destination.walkable == true)
{
pos += Vector3.up;
return true;
} else {
return false;
}
}
Now, this is proving to be a heck of a lot of work when randomly generating maps, and trying to get all the neighbours indexed with their neighbours is a lot of work. I would love to not have to do that, and rather check for neighbours, walkability, etc, on the fly, but I'm not sure how to approach this? Is there a way to arbitrarily check if there is a tile to the north of my current tile, for example?
If I should be linking each tile to all it's neighbours, is there ane xisting algorithm for terrain generation I can have a look at?
Thanks in advance.
Answer by Oniromancer · May 24, 2014 at 01:40 PM
Hi. This is my first answer ever, so take it with caution. First: checking "walkability" on the fly should be a matter of getting the script component on the target tile, and having the properties you need to read as public. Then again, I think is always good practice to have a matrix-like structure that represents the map AND that each tile knows who the neighbors are. This allows you to implement pathfinding algorithms like A* (and many others). I usually implement and algorithm in the start phase of my map representation, but I guess this can prove to be inefficient if the map is too big and you are randomly generating. (Maybe in that case you can implement the neighbor assignment during the generation phase, so you don't have to go twice over the whole matrix)
Your answer
