Jul '24 (edited) • VALUE
simple approach to 2D arrays in c
Came across this cool approach to handling 2D arrays in C which I thought might be nice to share.
The approach is basically using a 1d of size width*height of the array e.g:
say we have a 1d array of our tiles enum:
enum TILES tiles[TILES_WIDTH * TILES_HEIGHT];
we can just loop over it with a single index:
for(int i = 0; i < TILES_WIDTH * TILES_HEIGHT; i++) {
enum TILES tile = tiles[i];
// If we need the x and y values
int x = index % TILES_WIDTH;
int y = index / TILES_WIDTH;
draw_rect(v2(x * tile_size, y * tile_size), v2(tile_size, tile_size), color);
}
if we want to index into a given x and y coordinate we multiply the y index by the width of the array and add the x index:
tiles[y * TILES_WIDTH + x]
I've found this approach has been useful for tile/grid based games
EDIT: Thanks for the suggestion
10
9 comments
Louis Johnson
4
simple approach to 2D arrays in c
powered by
Ooga Booga Game Devs
skool.com/game-dev-grinders-8513
A group for game devs who want to ship great games from scratch in C, while mastering the ancient art of Caveman Programming
Build your own community
Bring people together around your passion and get paid.
Powered by