Domanda

Server owner had asked me to write a simple plugin for the server. All it requires is that if you click on a bookshelf with a written book in hand, it will open a chest. When the person closes that chest, all the books placed in it are destroyed.

I understand the basics of bukkit plugin developing, but the instructions on their website are quite complicated. I understand that I would have to register that the players item in hand is indeed a book with this code:

Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.WRITTEN_BOOK) {
// Do other stuff in here
}

However, if it would be easier for the plugin to be a button that is pressed and the book in hand is destroyed, would you please let me know and help me go about those steps.

È stato utile?

Soluzione

You could listen to PlayerInteractEvent, check if they right-click a bookshelf, then open a chest GUI... You could do it like this:

@EventHandler //ALWAYS use this before events
public void playerInteract(PlayerInteractEvent e){ //listen for PlayerInteractEvent
  if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK){ //make sure the player right-clicked a block
    if(e.getClickedBlock().getType().equals(Material.BOOKSHELF)){ //make sure the player right-clicked a bookshelf
      Player p = e.getPlayer(); //get the player
      if(p.getItemInHand() != null){ //make sure the player has something in their hand
        if(p.getItemInHand().getType().equals(Material.WRITTEN_BOOK)){ //check if the player has a written book in their inventory
          //Inventory inv = Bukkit.createInventory(null, <size (should be divisible by 9)>, "name"); //create the inventory
          //An example of creating the inventory would be:
          Inventory inv = Bukkit.createInventory(null, 36, "Disposal");
        }
      }
    }
  }
}

That should be all that you need to do. Just make sure that you register events in your onEnable() method using:

this.getServer().getPluginManager().registerEvents(new HandlerClassName(), this);

and make sure that the handler class implements Listener.

Pretty much, what the first code above is doing, is:

  • Listen for PlayerInteractEvent
  • Make sure that the player involved with the interact event Right Clicked a block
  • Make sure that the right-clicked block was a Book Shelf
  • Make sure that the item in the player's hand is not null
  • Make sure that the item in the player's hand is a Written Book
  • Create a new inventory named Disposal with 36 slots, or a 9 x 4 chest.

Then, when the player puts items in the chest, and closes it, the items will be destroyed!

If you would like it to just remove the book when the user right-clicks a chest, simply use:

p.setItemInHand(new ItemStack(Material.AIR));

Instead of this:

Inventory inv = Bukkit.createInventory(null, 36, "Disposal");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top