Tilemap Chunk Generation

Started by
2 comments, last by imontheverge 7 years, 8 months ago
I have a class TileChunk which at it's most basic contains a rectangle that surrounds the chunk, and four bools isLeftLoaded, isTopLoaded, etc. Using the rectangle I can determine which chunk the player is in.

What I want to do is create some kind of method which checks the current chunk the player is in, and if nothing is loaded then create new chunks that surround the sides that haven't been loaded. The problem I'm coming across is that using the four bool variables doesn't seem to work correctly. At initialization, I create 9 chunks to make a 3x3 starting area but some of the bool variables aren't being set correctly.

My question is how should I write a method which determines what chunks have loaded chunks adjacent to them? Every chunk is stored in a List, but other than using the bool variables I'm not sure what is the best way to do this.
Advertisement

I haven't done much work with chunks and such so you might want to take this with a grain of salt... but, rather than needing to keep up with a set of flags, why not check if a chunk is loaded directly? For example, each chunk could have a chunk id... such as Chunk_000_000 for the chunk at the origin, Chunk_001_000 for the chunk on the right etc.

Keep a list of Loaded Chunk Ids...

then in the loadChunk function add the current chunks id to the list of loaded chunks and in the unloadChunk function remove the chunk id from the list. This way you wouldn't have to worry about your flags getting out of sync... obviously there are better ways to create a chunk id... i just used that as an example.

I'm assuming that a chunk is supposed to be a Square region of 2D space? If so, then you can use a spatial hashing function to get a clue on the player's location.

Essentially, you take some side length L, and you divide that by the positional components and round them down.

So let A be a player's location.

(A.x_component / L) Round Down = Chunk X coordinate.

(A.y_component / L) Round Down = Chunk Y Coordinate.

So say I set the coordinate to the center of the chunk, being chunkwidth *tilewidth /2 and chunkheight *tileheight /2. Then in the hashtable, I check which chunk the player is in and then using an offset I check if the chunk has loaded chunks on the side and if not I load them.

Maybe this would work?

This topic is closed to new replies.

Advertisement