// Directions, I know I could've used BlockFace but this is simply personal preference
private final int[][] sides = new int[][] {
// up
new int[] {
0,
1,
0 },
// down
new int[] {
0,
-1,
0 },
// north
new int[] {
1,
0,
0 },
// south
new int[] {
-1,
0,
0 },
// east
new int[] {
0,
0,
1 },
// west
new int[] {
0,
0,
-1 } };
/**
* A method to move the location forward.
*/
private void execute(Location loc, Vector dir) {
Location to = loc.clone().add(dir); // get the target location
if (to.getBlock().getType() == Material.AIR) { // should also check for non-solid blocks to pass through like torches
loc.add(dir); // if nothing was hit, move the location forward and stop the method
return;
}
// we hit a block, let's see on which block the surface is.
for (int i = 0; i < sides.length; i++) { // for loop to check which side we hit
int[] addition = sides;
loc.add(addition[0], addition[1], addition[2]); // move location one block in the current iteration's direction
if (loc.getBlock().getType() == Material.AIR) { // check if there is a solid block in the current iteration's direction
loc.subtract(addition[0], addition[1], addition[2]); // if not, move the location back to it's original location and continue with the next iteration
continue;
}
// if statements to invert vector axis depending on what surface was hit.
if (i < 2) { if i is lower than 2, which means the side was either up or down
dir.setY(-dir.getY()); // invert respective axis
loc.subtract(addition[0], addition[1], addition[2]); // revert location back to original position
} else if (i < 5) { // if i is greater or equal to 2 and lower than 5, which means the side was either north or south
dir.setX(-dir.getX()); // invert respective axis
loc.subtract(addition[0], addition[1], addition[2]); // revert location back to original position
} else { // anything higher or equal to 5, which means the side was either east or west
dir.setZ(-dir.getZ()); // invert respective axis
loc.subtract(addition[0], addition[1], addition[2]); // revert location back to original position
}
}
loc.add(dir); // move location forward
}