1
\$\begingroup\$

I've created a tiled map that holds two layers, one for the tile type, and the other for whether it is solid or not. I plan on creating very big maps, and checking every tile seems like it would slow down my game immensely.

So lets say I had an array of integers. "0" representing solid, and "1" representing not solid. How would I check only the 8 surrounding integers instead of the whole array each update.

0 0 0

0 1 0

0 0 0

\$\endgroup\$
1
  • 1
    \$\begingroup\$ How to check surrounding tiles is trivial, see my answer for that. How to implement collision resolution is a much broader question that has too many variables to have a single solution. I suggest you try out your idea and see how well it works for you, then if you have specific questions about it, ask those here. I've removed the collision resolution portion of your question. \$\endgroup\$
    – House
    Jan 3, 2014 at 21:09

2 Answers 2

6
\$\begingroup\$

Checking the surrounding tiles is pretty simple. You can do it pretty easily in a nested for loop:

for(int i = x-1; i <= x+1; i++) {
    for(int j = y-1; j <= y+1; j++) {
        if(i != x || j != y) { //ignore the center tile
            //process tile (i,j)
        }
    }
}

This will loop through each tile surrounding tile (x, y). You'll want to add some bounds checking as well for when you're looking at a tile on the edge of your map.

\$\endgroup\$
4
\$\begingroup\$

Another option is to hardcode the list of the surrounding tiles offsets. E.g.:

// Somewhere at init:
Object[][] xyoffsets = {{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}};

// ...

// Later:
for(Object[] xyoffset : xyoffsets) {
    int i = x + xyoffset[0];
    int j = y + xyoffset[1];
    // process tile (i,j)
}

This avoids an unnecessary if and allows to easily change the order in which tiles are processed, but also adds the cost of an extra table.

\$\endgroup\$
1
  • \$\begingroup\$ This is a great strategy for many things, like implementing A*. Setting the order the tiles are checked is sometimes pretty important and this is also a great way to only check the orthogonals or diagonals. \$\endgroup\$
    – House
    Jan 4, 2014 at 16:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .