1.14.4 Finding clear block in a radius

Discussion in 'Spigot Plugin Development' started by DarkKnights22, Jan 12, 2020.

  1. From a given location, how do I find the location in a given radius that the block is null or air?

    Code (Java):
    for (int x = 0; x <= 1; x++) {
                for (int z = -0; z <= 1; z++) {
                    Block block = getBeds().get(target.getUniqueId()).getBlock().getRelative(x, getBeds().get(target.getUniqueId()).getBlockY(), z);
                    if (block != null && block.getType() != Material.AIR)
                        player.teleport(block.getLocation());
                }
            }
    This is what I'm going off of. Needs to have same y.
     
  2. Didn't test but should work fine.

    Code (Java):
      public static Optional<Block> getNextValidBlockInRadius(Block block, int radius, Predicate<Block> validation) {
        Block foundBlock = null;
        int y = block.getY();
        OuterLoop:
        for (int x = -radius; x <= radius; x++) {
          for (int z = -radius; z <= radius; z++) {
            Block next = block.getRelative(x, y, z);
            if (validation.test(next)) {
              foundBlock = next;
              break OuterLoop;
            }
          }
        }
        return Optional.ofNullable(foundBlock);
      }


    Usage:
    Code (Java):
        Block middle;
        int radius;
        getNextValidBlockInRadius(middle, radius, (block) -> block.getType() == Material.AIR);
     
  3. How would I get the location of what it returns?
     
  4. FrostedSnowman

    Resource Staff

    it returns an Optional<Block>. use Optional::ifPresent then Block::getLocation.