Search code examples
eventsevent-handlingminecraftbukkit

Custom explosion after BlockPlaceEvent


So I'm trying to make a nuclear bomb in Minecraft so I tried to make a custom TNT block on placement, but I can't seem to trigger the action of creating the explosion at the block location. May I have some help?

Here's the code...

package com.TheRealBee.Bows.Event9;

import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;

public class EventManager9 implements Listener {
        @EventHandler
        public static void onBlockPlace(BlockPlaceEvent e) {

            Block b = e.getBlock();
            Location blocklocation = b.getLocation();
            if (e.getBlockPlaced().equals(ChatColor.AQUA+"Nuclear bomb")){
                blocklocation.getWorld().createExplosion(blocklocation, 5, true);
            }
        }
    }


Solution

  • Your issue is that you're checking for equality between a Block (the result of e.getBlockPlaced()) and a string. These two will never be equal and so your condition is not met.

    You could change your condition so that it checks the ItemStack in the player's hand when the block was placed. You also didn't check for the block type and so I've added a check for TNT in my example code below but you can just remove that for it to work with any block with the custom name.

        @EventHandler
        public void onNukePlace(BlockPlaceEvent e){
            // Return if it's not TNT, doesn't have ItemMeta or doesn't have a custom dispaly name
            if(!e.getBlock().getType().equals(Material.TNT) || !e.getItemInHand().hasItemMeta() || !e.getItemInHand().getItemMeta().hasDisplayName())
                return;
            // Return if the item display name is not correct
            if(!e.getItemInHand().getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Nuclear bomb"))
                return;
            // Create the explosion
            e.getBlock().getLocation().getWorld().createExplosion(e.getBlock().getLocation(), 5, true);
        }
    

    However, this will cause the explosion to happen instantaneously on placement, if that's not desired, you can use a runnable like runTaskLater. You may wish to manually remove the block that the player placed as if, for example, you make your 'Nuclear bomb' using bedrock, the explosion won't get rid of it.