Chunks and Collisions

I am making a game, and I am loading it in chunks. AKA: I load only 15 320240 pixel parts of the world at the time (2015 blocks). My only problems are collisions. They work properly only in the chunk (0, 0). Chunks in the same quadrant have a weird offset, like being 1 block above where it should be. In the other quadrants, it doesn’t work at all, because the collisions keep going to -1, which is out of bounds for my grid.

Here is my code, it is designed to take world coordinates and turn them into a chunk coordinate and then a chunk’s block coordinate:

public Block getBlock(float x, float y)
	{
		int chunkX = (int)( (x-(x%320))/320 );
		int chunkY = (int)( (y-(y%240))/240 );
		Chunk chunk = getChunk(chunkX, chunkY);
		
		int blockX = (int)( x-(chunk.getX()*320) );
		int blockY = (int)( y-(chunk.getY()*240) );
		return chunk.getBlock(blockX, blockY);
	}

I want to know why it isn’t working, the code seems perfectly sound, and the results a little random. It would be a great help if you knew why, and told me!

It could be because you’re doing a modulus on a floating point number. Since floats aren’t stored exactly, it could lead to slight variations in results compared to what you would expect. This might explain the weird off by one errors.

When x is negative, x%320 will be negative too. Because of this, when -320 < x < 320, chunkX = 0, so this chunk is 640 blocks wide. Is it intentional?

It seems like the whole operation of (x - (x %320) / 320) could be removed and replaced with Math.floor(x/320). At least, I think the effect you’re going to there.

x = 330
x % 320 = 10
x - (x % 320) = 320
x - (x % 320) / 320 = 1
Math.floor(x / 320) = 1

The second one feels like you’re doing X % 320.

x = 330
chunk = 1
chunk * 320 = 320
x - chunk*320 = 10

I think that taking care of these issues might help figure out the problem. You’re using an excess of imprecise mathematics, that will cause problems and probably help confuse where the actual issue is coming from. :3

Thank you for explaining it, the collision works perfectly now. :smiley:

Also, is there any way to make this work when it reaches the negatives? I just tried it by making it absolute, but I knew that wouldn’t work because the number line is reversed, but the chunks have their independent grids, so they aren’t affected. So I end up with seemingly random collisions. Any ideas?

No, this is not intentional, but I also haven’t had any problems with it yet.