EntityExplodeEvent

Discussion in 'Spigot Plugin Development' started by GarageCode, Jul 3, 2018.

Thread Status:
Not open for further replies.
  1. I need to break OBSIDIAN block naturally, but i can't do that, i use this code to do that...

    Code (Java):
     
    @EventHandler
    public void on(EntityExplodeEvent e){
        if (e.getEntity().getType().equals(EntityType.PRIMED_TNT)) {
            e.blockList().forEach(k -> {
                if (k.getType().equals(Material.OBSIDIAN)) {
                    k.breakNaturally();
                    e.setCancelled(true);
                }
            });
        }
    }
     
    What i do wrong ?
     
  2. You're using forEach, yet you use an if statement. Use the filter feature of streams to avoid this.
    Also, your event cancel is IN the forEach, meaning you're setting it to canceled for every obsidian block that's "broken".
    I'm going to assume you aren't trying to make TNT that ONLY breaks obsidian, so I would recommend not canceling this event at all.
    With these ideas put together, your code would look a bit like this:
    Code (Java):
    @EventHandler
        public void onExplode(EntityExplodeEvent event) {
            if (event.getEntity() instanceof TNTPrimed) {
                event.setCancelled(true);
                event.blockList().stream()
                        .filter(block -> block.getType() == Material.OBSIDIAN)
                       .forEach(Block::breakNaturally);
            }
        }
    However, now you're probably thinking "well hold on now, my tests showed the blocks breaking from the explosion regardless of if the event is cancelled or not." You are correct, for the specific reason being that in your code the event is NEVER cancelled, because event.getBlockList() will not contain any obsidian. event.getBlockList() only contains the blocks already "marked" as to be blown up from the explosion, and since obsidian is completely resistant to explosions, there will never be obsidian within that list.
    So, what the solution?
    Artificially grabbing the obsidian blocks around the TNT entity.
    This method will return a list of blocks set to be destroyed by the explosion. I'd choose a radius of, perhaps 2? simply make the "center" the location of the TNT entity. Break the blocks in that list naturally, and for some extra flare set the drops to only spawn at the percent rate of the event's yield value.
     
    • Agree Agree x 1
    • Winner Winner x 1
  3. Thank you! You saved me xD
     
Thread Status:
Not open for further replies.