Make AI preferably follow a road that's defined in tilemap (2D)

Hi all,

Sorry if this has been asked before, I tried searching and I don’t know if I used correct search terms, but I couldn’t find anything.

Let me explain my situation:
I have a 2D topdown game, based in a western town. I have 2 types of Npc, a villager on foot and a villager on horse. Right now, everyone just walks wherever they want on the roads. But I’d like villagers to walk on the sidewalk (which are located next to buildings) and if they are on horse, they can do both, but should prefer walking on the road asap instead of the sidewalk.

I have found some suggestions marking nodes with tags and, for example, giving penalties for the sidewalk as a horse. And a penalty for the road as a villager on foot, so they will prefer to walk on the sidewalk if they find themselves on a road by accident.

But my main issue is… how can I get this data from my tilemap? In the tilemap I have put a “sidewalk” and “road” texture on my grid, but how can I tell this to the a* grid?

Maybe it’s a real simple issue, but I don’t really know where to look as I don’t know what search terms I need to use.

Hi

You are entirely correct in that the best way to do it is to set tags on the different nodes and then have a penalty for traversing non-road nodes.

There is no built-in solution for getting the data from the tilemap to the A* grid, but you can use the Tilemap.GetTile method to get the tile at a specific coordinate, and then you can mark the corresponding node with a tag.
See this example: https://arongranberg.com/astar/docs/graph-updates.php#direct

Hey Aron,

Thanks for the incredibly quick reply!

You have provided me with very useful links, I think I can figure it out now.

I will probably, when starting the scene, loop through all nodes once, like in the example, and then check the tilemap if that’s a “road tile” or not, to see if I want to tag it.

Is that actually a common/recommended practice? It’s a static game so the tiles will never change.

Yes, it seems like a decent way to do it.
There are built-in methods from getting the penalty information from a texture, but not from a tilemap at the moment. So this approach seems reasonable.

Alright that’s good to know :grinning:

That’s probably how I’m going to do it then, thanks! Sounds like creating a texture based on the roads in the tilemap and getting penalty information from there is also an option for the future.

I’m just starting out with Unity as a hobby, but I will consider buying the Pro version of a* once my knowledge improves a little.

One thing though is that the texture can only be used to assign a raw penalty, not a tag. So if you have different unit types which need different penalties, then using tags is probably better.

Okay! Sounds good.
The pro version is on sale for 50% off right now though (for about another week) during the asset store black friday sale.

1 Like