1.17.x Checking If Block Is Safe To Place

Discussion in 'Spigot Plugin Development' started by AllyTally, Jun 21, 2021.

  1. I'm working on a plugin that involves placing blocks like the player does, and so far I have
    Code (Java):
              Block relativeBlock = event.getClickedBlock().getRelative(event.getBlockFace());
              if (relativeBlock.isEmpty()) {
                relativeBlock.setType(event.getClickedBlock().getBlockData().getMaterial());
                Sound placeSound = relativeBlock.getBlockData().getSoundGroup().getPlaceSound();
                relativeBlock.getWorld().playSound(relativeBlock.getLocation(), placeSound, 1f, 0.8f);
              }
    which will place a block at the correct location and play a sound.
    It'll only does this if the block is empty... which is almost what I want, however I'd like to use the same checks vanilla Minecraft does, with things like checking if there's entities before placing, being able to replace tall grass or fluids with blocks, or making sure you can't place blocks in the air that you normally can't (for example, a floating flower.)
    The first and last things there are very important, and I was wondering if Spigot itself has a way to do these checks or if I have to hardcode things myself.

    Basically, I just need to check if a player is able to place a block at a location or not. It can't be inside of an entity, it can't replace a block (unless tall grass or a liquid) and it can't be in an invalid position (like flowers floating). I'd like to use vanilla Minecraft's check for this.
     
    #1 AllyTally, Jun 21, 2021
    Last edited: Jun 21, 2021
  2. Maybe Material#isSolid() is what you're looking for? This should return true if the block material has a collision box, so it returns false on blocks like tall grass, liquids, but probably also flowers. You might have to hard-code this.
    As for entities, you can use World#getNearbyEntities() and give a very small radius. If the size of the collection this returns is greater than 0, there's an entity in the way. You can also use predicates to narrow this down to specifically LivingEntities