Spiral chunk loading

This commit is contained in:
Németh Noel 2021-05-05 17:05:22 +02:00
parent 78937a6b0b
commit 5b41f3ffd0

View File

@ -163,18 +163,45 @@ public final class ChunkUtils {
*/ */
@NotNull @NotNull
public static long[] getChunksInRange(@NotNull Position position, int range) { public static long[] getChunksInRange(@NotNull Position position, int range) {
range = range * 2; long[] visibleChunks = new long[MathUtils.square(range * 2 + 1)];
long[] visibleChunks = new long[MathUtils.square(range + 1)];
final int startLoop = -(range / 2); int xDistance = 0;
final int endLoop = range / 2 + 1; int xDirection = 1;
int counter = 0; int zDistance = 0;
for (int x = startLoop; x < endLoop; x++) { int zDirection = -1;
for (int z = startLoop; z < endLoop; z++) { int len = 1;
final int chunkX = getChunkCoordinate(position.getX() + Chunk.CHUNK_SIZE_X * x); int corner = 0;
final int chunkZ = getChunkCoordinate(position.getZ() + Chunk.CHUNK_SIZE_Z * z);
visibleChunks[counter++] = getChunkIndex(chunkX, chunkZ); for (int i = 0; i < visibleChunks.length; i++) {
final int chunkX = getChunkCoordinate(xDistance * Chunk.CHUNK_SIZE_X + position.getX());
final int chunkZ = getChunkCoordinate(zDistance * Chunk.CHUNK_SIZE_Z + position.getZ());
visibleChunks[i] = getChunkIndex(chunkX, chunkZ);
if (corner % 2 == 0) {
// step on X axis
xDistance += xDirection;
if (Math.abs(xDistance) == len) {
// hit corner
corner++;
xDirection = -xDirection;
}
} else {
// step on Z axis
zDistance += zDirection;
if (Math.abs(zDistance) == len) {
// hit corner
corner++;
zDirection = -zDirection;
if (corner % 4 == 0) {
len++;
} }
} }
}
}
return visibleChunks; return visibleChunks;
} }