Solved How to get the block behind a button that was pressed.

Discussion in 'Spigot Plugin Development' started by Stan_K_YT, Jan 23, 2020.

  1. I want to check if the block behind a pressed button is an ice block. Right now I have this:

    Code (Java):
    public class ButtonListener implements Listener {

        @EventHandler
        public void onButtonPress(PlayerInteractEvent e) {
            if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && e.getClickedBlock().getType().equals(Material.STONE_BUTTON)) {
                e.getPlayer().sendMessage("You clicked a stone button.");
            }

        }
    }
     
  2. SteelPhoenix

    Moderator

    Get the BlockFace the button is attached to (a button's BlockData is Directionable), and then use Block#getRelative(BlockFace) to get the block it's attached to.
     
  3. Do this:
    Code (Java):
    final Switch button = (Switch) e.getClickedBlock().getBlockData();
    BlockFace face = button.getFacing();
    switch (button.getFace()) {
        case FLOOR:
            face = BlockFace.UP;
            break;
        case CEILING:
            face = BlockFace.DOWN;
            break;
         }
    final Block behind = e.getClickedBlock().getRelative(face.getOppositeFace());
    You also need to check for the face since if the button is on top of a block or below it, the face will still be only one of North, east, south or west.