In my voxel game, I'm trying to spawn chunks in all directions. But since my world starts at 0,0,0
, some chunks can spawn at negative positions like -1,0,-1
.
My chunks are 16x16x16
size.
When generating(or not) a block, somewhere in the process, I need to find what block is at position A(xyz 0-15
) in chunk B(xyz -max +max
), based on block's world position.
So for example, block at world position(can be xyz-max +max
) 1, 0, 1
should give me chunk 0, 0, 0
and block's relative position inside chunk is 1, 0, 1
.
block at world position -1, 0, -1
should give me chunk -1, 0, -1
and index of block relative to this chunk 15, 0, 15
.
But as you see, there is an inconsistency and loss of symmetry(-1 relative to 0 gives -1 and 1 relative to 0 gives 0) relative to 0, 0, 0
, that I can't figure out how to fix.
Currently I find relative index in chunk from world position using this:
int size = 16;
int x = -1;
int y = 0;
int z = -1;
int chunkRelativeX = x % size;
int chunkRelativeY = y % size; //0
int chunkRelativeZ = z % size;
if (x < 0)
{
chunkRelativeX += size; //15
}
if (z < 0)
{
chunkRelativeZ += size; //15
}
And I find chunk position itself using:
int chunkPosX = Mathf.FloorToInt((float)x / size); //-1
int chunkPosY = Mathf.FloorToInt((float)y / size); //0
int chunkPosZ = Mathf.FloorToInt((float)z / size); //-1
Problem is, with positives, its correct, since before 1st chunk comes 0st, but before -1st chunk, doesn't come 0st.
I'm really confused and not sure what to do :D
Thanks in advance.
& 15
instead of modulo% 16
? \$\endgroup\$