Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm making a tile engine for 2D games (seen from the top). Basically the world is composed of a grid of tiles. Now I want to put for instance NPCs that can move on the map.

What do you think is best: 1) each tile has a pointer to the NPC that is on its tile, or a NULL pointer 2) having a list of NPCs, and they have the coordinates of the tile they are on. 3) something else?

1) is faster for collision detection but it would use much more memory space and it is slower to find all NPCs in a map. 2) is the opposite.


share|improve this question
up vote 11 down vote accepted

Why not both? There are times when you'll want to look to see if there's any NPC on a specific tile (such as for collision detection, as you mentioned), and other times when you'll want to iterate over all the NPCs in the world (such as for running their AI methods every frame).

A pointer per tile is not that much memory unless you're working on a memory-constrained platform or you have a really huge map.

share|improve this answer
+1 I tend to agree with this, however @lezebulon, I suggest that you encapsulate any logic that needs to update both together, as early as possible. That is, when a player leaves a tile, there should be one atomic operation (function call) to remove both pointers, player-to-tile and tile-to-player, at the same time. And the same for when a player arrives on a tile, do the two pointer assignments together. This will save you some potential chaos where references don't agree with one another, i.e. one exists while the other does not. – Arcane Engineer Nov 12 '11 at 21:07

How do you handle collisions with the map? If you have a collision layer, a very easy way would be to first create a list of NPCs with coordinates indicating on which tile they are on and then iterating through that list and marking the collision layer tile under the NPC as a collision tile. That way, the collisions against NPCs would be handled at the same time as rest of the map. That is, of course, if the NPCs don't move...

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.