John Davidson

php - Pocketmine: BlockPlaceEvent, add items when chest is placed

0 comments
Message:


What I want to do is some kit, whenever I place a chest, it will fill items inside it. This is my code so far.


public function onBlockPlace(BlockPlaceEvent $event): void {
$dataConfig = CustomConfig::get("data.yml");
$block = $event->getBlock();
$item = $event->getItem();
$player = $event->getPlayer();
$server = $player->getServer();
$world = $player->getWorld();


if ($item->getId() === ItemIds::CHEST && $item->getMeta() !== 0) {
$chest = new Chest($world, $block->getPosition());
$kits = $dataConfig->getConfig()->getAll(true);
$meta = $item->getMeta();


// add items on the chest
foreach ($kits as $id) {
$kit = $dataConfig->getConfig()->get($id);
if ($kit["meta"] === $meta) {
$chest->setName($kit["display"]);
$items = $dataConfig->getConfig()->getNested("$id.chest.items");


foreach ($items as $key => $value) {
$itemKit = ItemKit::fromArray($value, $key);
$chest->getInventory()->addItem($itemKit->getItem());
}


break;
}
}


$world->addTile($chest);
$world->setBlock($block->getPosition(), $block);
$item->pop();
$event->cancel();
}
}

It would add the items on the chest, and show the chest in the world, the problem is that now the default behavior is gone, for example, the blockplace sound, pairevent, etc. But if I were to remove the event.cancel(), and have this:


            $world->addTile($chest);
// $world->setBlock($block->getPosition(), $block);
// $item->pop();
// $event->cancel();

The title of the chest is the name of the item. Like for example the name of the chest item is Awesome kit, I want the title of the chest tile to be just Awesome, but what happened is the title is the Awesome kit.


This is the result of those two:


            $world->addTile($chest);
$world->setBlock($block->getPosition(), $block);
$item->pop();
$event->cancel();


            $world->addTile($chest);
// $world->setBlock($block->getPosition(), $block);
// $item->pop();
// $event->cancel();


How do I achieve the first one, but still having the default behavior?



My Answer:
"chest_items.yml"); $block = $event->getBlock(); if($block->getId() === BlockIds::CHEST) { $inventory = $block->getInventory(); $items = $dataConfig->get("items"); foreach($items as $item) { $item = Item::fromString($item); $inventory->addItem($item); } } }_In this code, I am checking if the block being placed is a chest, and if it is, I am getting the inventory of the chest and adding items to it from a configuration file called "chest_items.yml". Make sure to create this configuration file and add the items you want to add to the chest in the format "item_id:item_meta:count".

Rate this post

3 of 5 based on 6653 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us