Search code examples
javabukkit

How to change a piston direction?


I need some help to change a piston direction while placing it programmatically.

I use this method to set my block type to a piston:

block.setType(Material.PISTON_BASE);

But I can't find a method to change its direction, and point it down.


Solution

  • Bukkit has utility methods to change facing of the piston using the MaterialData api, this api can be used as follows:

    Block block = ....;
    BlockState state = block.getState();
    PistonBaseMaterial piston = (PistonBaseMaterial)state.getData();
    
    piston.setFacingDirection(BlockFace.NORTH);
    piston.setFacingDirection(BlockFace.SOUTH);
    piston.setFacingDirection(BlockFace.WEST);
    piston.setFacingDirection(BlockFace.EAST);
    piston.setFacingDirection(BlockFace.UP);
    piston.setFacingDirection(BlockFace.DOWN);
    
    state.setData(piston);
    state.update();
    

    Outside of the direction, we can also power/unpower the piston by calling piston.setPowered(true/false);. We can also easily check if the piston is a sticky one by calling the method piston.isSticky(), without relying on the other deprecated methods since we are no longer using "magic id's" anymore.