Cleaner, less resource heavy method for checking for blocks in a given radius at a given location

Hey there, title says it all. So my current way for finding a blocktype in a radius is starting with some nested for loops:

for (int x=-(radius);x<radius;x++)
  for (int y=-(radius);y <radius;y++)
    for (int z=-(radius);z <radius;z++)

Then inside the loops I create a new location based on my origin location:

Location newLoc = new Location(oldLoc.getExtent (), oldLoc.getBlockX() +x, oldLoc.getBlockY()+y,oldLoc.getBlockZ()+z);

BlockType bloc = newLoc.getBlockAt().getType();
If(bloc == BlockTypes.CHEST) {
   //DO STUFF
}

And this is what I’ve done to find a chest in this radius. However, what I’m asking is, is there a better way? Perhaps one that doesn’t require creating a new location every loop through? Thanks I’m advance for the help.

Here is an example that avoids creating a lot of objects. It think it’s one of the lightest possible. It’s directly using Extent which represents a world containing blocks and it uses ints to optimize memory usage. English is not my native language. I hope the example will be more clear.

		Extent extent = loc.getExtent();
		Vector3i pos = loc.getBlockPosition();
		int x = pos.getX(), y = pos.getY(), z = pos.getZ();

		for (int dx = -radius; dx < radius; dx++) {
			for (int dy = -radius; dy < radius; dy++) {
				for (int dz = -radius; dz < radius; dz++) {
					BlockType type = extent.getBlockType(x + dx, y + dy, z + dz);
					if (type == BlockTypes.CHEST) {
						// DO STUFF
					}
				}
			}
		}
1 Like

Thanks much, this method seems a lot Cleaner! :relaxed:

Extent actually has methods in place to iterate through it. Figure out the dimensions first, call getExtentView to get a resized Extent to iterate over, and then call getBlockWorker to get the BlockVolumeWorker. It has various specific methods to invoke common operations, such as mapping one BlockVolume (an Extent superclass) onto another, or filling the volume based on some algorithm, but if none of these are what you are doing then iterate will work fine. This is the most optimized access possible.