# Looping through blocks in a certain radius

Discussion in 'Plugin Development' started by Jaker232, Jan 4, 2014.

Not open for further replies.
1. Offline

### Jaker232

Say I have the following scenario: I (the player) am in the center, and I want to get all the block in a 3 by 3 radius, having no y difference. I'd need to iterate through the x and z axis, leaving the y completely untouched. This is what I have so far

Code:
```private void xxxxx(Block block) {
Block end = block.getLocation().add(endInt, 0, endInt).getBlock();
int startX = start.getX();
int startZ = start.getZ();
int endX = end.getX();
int endZ = end.getZ();

}```

#1
2. Offline

### AGuyWhoSkis

Here's a method I created, it gets all blocks (in a cube shape) around a given "radius" (really just a max distance from the starting location). Note that you will have to modify this, just take out the for loop which adds to the y value I guess.

Code:
```    public static void methodNameHere (Location loc, int r) {

int X = loc.getBlockX();
int Y = loc.getBlockY();
int Z = loc.getBlockZ();

int x = (int) (X -r);
int y = (int) (Y -r);
int z = (int) (Z -r);

int bx = x;
int bz = z;

for (int i=0; i<r*2+1; i++) {
for (int j=0; j<r*2+1; j++) {
for (int k=0; k<r*2+1; k++) {
//Code here
Block b = loc.getWorld().getBlockAt(x,y,z);
x++;
}
z++;
x = bx;
}
z = bz;
x = bx;
y++;
}
}```

#2
3. Offline

### Nateb1121

Jaker232
All you'd need to do, to get your desired affect from AGuyWhoSkis 's code, is remove the Y changing loop.

#3
AGuyWhoSkis likes this.
4. Offline

### AGuyWhoSkis

Jaker232 Let me know if you want me to explain how it works

#4
5. Offline

### Jaker232

AGuyWhoSkis Can you elaborate on how it works? I seem to be a bit daunted by the code.

#5
6. Offline

### The Gaming Grunts

Jaker232
It basically gets the x, y, and z coordinates from a given location and then subtracts a number (the radius) from each value.

7. Offline

#7
8. Offline

### The Gaming Grunts

Jaker232
Change the minus sign to a plus sign...

9. Offline

### AGuyWhoSkis

Code:
```    public static void methodNameHere (Location loc, int r) {

//Get the original coordinates of the location input (for easier use, that's all)
int X = loc.getBlockX();
int Y = loc.getBlockY();
int Z = loc.getBlockZ();

//Get the coordinates of the corner of the cuboid
int x = (int) (X -r);
int y = (int) (Y -r);
int z = (int) (Z -r);

//Save the corner values of x and z values for use later (b stands for base)
int bx = x;
int bz = z;

//3 for loops are used here; 1 for each coordinate (x, y, and z) Given a radius of r would make each loop happen 2*r+1 times; 2*r to get the diamater, and +1 to include the block in the middle.

for (int i=0; i<r*2+1; i++) {

for (int j=0; j<r*2+1; j++) {

for (int k=0; k<r*2+1; k++) {

//Code here
Block b = loc.getWorld().getBlockAt(x,y,z);

x++;

}
z++;

//reset x back to the "corner" value we got at the beginning
x = bx;
}

//reset z
z = bz;

//reset x
x = bx;