DEV Community

Cover image for Cell iterator - Part 1 (Brain dump)
Jack Le Hamster
Jack Le Hamster

Posted on

Cell iterator - Part 1 (Brain dump)

For my game engine, one of the ideas I'm exploring is the idea of organizing the world into a grid of cells, containing sprites.

Each cell will have a fixed width, height, depth. In a 3d world, it can be visualized as a cube.

Cell cube

The main goal here is that I need to iterate through elements contained in a massive world. I'm not gonna bother with sprites several kilometers away, only the ones in the surroundings of a player.

Or perhaps I still need to render mountains... but let's keep that issue for later.

At close proximity, we can just poll a sprite providers and ask:

  • At cell (x,y,z), what sprites do we find?

Then poll that for all sprites at proximity.

I could just do some kinda of loop for all the cell positions to poll:

for (let x = -100; x < 100; x++) {
  for (let y = -100; y < 100; y++) {
    for (let z = -100; z < 100; z++) {
       pollCell(player.x + x, player.y + y, player.z + z);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

But here's the thing. Cells that are closer, if fully opaque, should make the cells behind disappear, and therefore we can skip them.

So it's best to iterate outwards, starting from the closest cells to the ones further away. Once we figure out that a cell is opaque, we know we can skip iterating the ones behind.

Cell order

There must be some way to iterate in such a way.

More on this later...

Top comments (0)