简体   繁体   中英

Chunks don't load

I try to create a game like minecraft but I have a problem with chunk loading.. Right now, I only check if the player is in an unloaded chunk and if this is true, I load this chunk:

Vector2f cameraPos = new Vector2f(camera.getTransform().getPos().getX(), camera.getTransform().getPos().getZ());
Vector3f currentChunkPos = new Vector3f((float) Math.floor(cameraPos.getX() / Chunk.WIDTH - 0.499f) * Chunk.WIDTH, 0, (float) Math.floor(cameraPos.getY() / Chunk.LENGTH - 0.499f) * Chunk.LENGTH);
System.out.println(currentChunkPos);
if(findChunk(currentChunkPos) == null) {
    loadedChunks.add(new Chunk(currentChunkPos, noise));
}

findChunk():

public Chunk findChunk(Vector3f pos) {
    for(Chunk chunk : loadedChunks) {
        Vector3f cpos = chunk.getTransform().getPos();
        if(pos.getX() == cpos.getX() && pos.getY() == cpos.getY() && pos.getZ() == cpos.getZ()) {
            return chunk;
        }
        if((pos.getX() < cpos.getX()) || (pos.getZ() < cpos.getZ()) || (pos.getX() > cpos.getX() + Chunk.WIDTH) || (pos.getZ() > cpos.getZ() + Chunk.WIDTH)) {
            continue;
        }
        return chunk;
    }
    return null;
}

But the problem is, sometimes the chunk you are in gets loaded directly when you go in, sometimes the chunk gets loaded if you are in the middle and half of the chunks don't load... Does someone know what I'm doing wrong?

As you're only storing a single X , Y and Z position for the chunk plus the sizes then comparing the users position in the world, chunks will only be loaded in front of the user if the user is moving 'forward' in the correct X , Y and Z position, otherwise your if condition won't be met because the user's X will be higher than the chunk X .

What you need to do is have each chunk store a 'Chunk number' for X and Y . Let's say your chunks are 50x50, then you might have them numbered like so:

块数

Then to work out the chunk from the world position you'd use:

final int chunkSize = 50;

final int[] worldPositions = {241, 186, 30};
final int chunkX = worldPositions[0] / chunkSize;
final int chunkY = worldPositions[1] / chunkSize;
System.out.println("X: " + chunkX + ", Y: " + chunkY); //Output: X: 4, Y: 3

So you can then load that chunk and every chunk that surrounds it too by adding and subtracting 1 from each value. You also shouldn't need a chunk Z as a chunk is everything in the X and Y area regardless of how high it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM