In a tile based game, how would I check if I am next to another tile?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jobax

E.g. I have a top down sprite that can move tile to tile with each move key. If I move next to an “NPC” placed on the map, how do I check for this? Basically nothing to do with collision (just needs to be in the tile next to it).

I think I have to use get_cellv but I’m not sure how I would also check for a particular tile id. Thanks.

:bust_in_silhouette: Reply From: pospathos

You should first check tile position of an NPC: first convert NPC’s pixel position to TileMap position with TileMap.world_to_map(NPC.position) and store NPC’s position in array or something like that. Then check if Player position is near (one Cell away) that position: TileMap.world_to_map(Player.position + Vector(0,CellSize)) - this will give you Tile Position bellow the Player (you should check all direction that you need). If this two TileMap coordinates are same then Player is above NPC.

Thanks got it working with your idea.

jobax | 2018-03-13 20:32

:bust_in_silhouette: Reply From: rikkiprince

If you want to answer this in 1 conditional statement, regardless of which direction the NPC is from the player avatar, try this:

player.distance_to(npc) <= 1

(where player and npc are Vector2s of the tile position on the tilemap, though you could do something similar with co-ordinates if needed).

Basically this measures the euclidean distance between the two, and in tile-space that distance would be equal to 1 if you’re either of the spaces horizontally or vertically adjacent to the NPC.

If you wanted to include diagonals, that would be equal to sqrt(2), so 1.41, so if you did:

new_position_on_map.distance_to(destination) < 1.5

you’d get what you wanted.