Skip to content

Instantly share code, notes, and snippets.

@hnOsmium0001
Last active June 14, 2019 21:16
Show Gist options
  • Save hnOsmium0001/50fa196358e31a32efe1982f0d8251d5 to your computer and use it in GitHub Desktop.
Save hnOsmium0001/50fa196358e31a32efe1982f0d8251d5 to your computer and use it in GitHub Desktop.
Finding relative direction between two BlockPos, assuming they are neighbors
// Inlined because apparently applications of pure function with constants are not considered constants
private static final int DOWN_BITS = 0b010100; // calculateDirectionBits(0, -1, 0)
private static final int UP_BITS = 0b010110; // calculateDirectionBits(0, 1, 0)
private static final int NORTH_BITS = 0b010001; // calculateDirectionBits(0, 0, -1)
private static final int SOUTH_BITS = 0b011001; // calculateDirectionBits(0, 0, 1)
private static final int WEST_BITS = 0b000101; // calculateDirectionBits(-1, 0, 0)
private static final int EAST_BITS = 0b100101; // calculateDirectionBits(1, 0, 0)
private static int calculateDirectionBits(int dx, int dy, int dz) {
// Add 1 to make all offsets positive to avoid dealing with complement bits
return ((dx + 1) << 4) | ((dz + 1) << 2) | (dy + 1);
}
public static Direction relativeDirection(BlockPos center, BlockPos neighbor) {
int dx = neighbor.getX() - center.getX();
int dy = neighbor.getY() - center.getY();
int dz = neighbor.getZ() - center.getZ();
switch (calculateDirectionBits(dx, dy, dz)) {
case DOWN_BITS:
return Direction.DOWN;
case UP_BITS:
return Direction.UP;
case NORTH_BITS:
return Direction.NORTH;
case SOUTH_BITS:
return Direction.SOUTH;
case WEST_BITS:
return Direction.WEST;
case EAST_BITS:
return Direction.EAST;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment