use of net.minecraft.world.entity.item.ItemEntity in project MinecraftForge by MinecraftForge.
the class ForgeInternalHandler method onEntityJoinWorld.
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event) {
Entity entity = event.getEntity();
if (entity.getClass().equals(ItemEntity.class)) {
ItemStack stack = ((ItemEntity) entity).getItem();
Item item = stack.getItem();
if (item.hasCustomEntity(stack)) {
Entity newEntity = item.createEntity(event.getWorld(), entity, stack);
if (newEntity != null) {
entity.discard();
event.setCanceled(true);
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getWorld().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getWorld().addFreshEntity(newEntity)));
}
}
}
}
use of net.minecraft.world.entity.item.ItemEntity in project MinecraftForge by MinecraftForge.
the class ItemHandlerHelper method giveItemToPlayer.
/**
* Inserts the given itemstack into the players inventory.
* If the inventory can't hold it, the item will be dropped in the world at the players position.
*
* @param player The player to give the item to
* @param stack The itemstack to insert
*/
public static void giveItemToPlayer(Player player, @Nonnull ItemStack stack, int preferredSlot) {
if (stack.isEmpty())
return;
IItemHandler inventory = new PlayerMainInvWrapper(player.getInventory());
Level world = player.level;
// try adding it into the inventory
ItemStack remainder = stack;
// insert into preferred slot first
if (preferredSlot >= 0 && preferredSlot < inventory.getSlots()) {
remainder = inventory.insertItem(preferredSlot, stack, false);
}
// then into the inventory in general
if (!remainder.isEmpty()) {
remainder = insertItemStacked(inventory, remainder, false);
}
// play sound if something got picked up
if (remainder.isEmpty() || remainder.getCount() != stack.getCount()) {
world.playSound(null, player.getX(), player.getY() + 0.5, player.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, ((world.random.nextFloat() - world.random.nextFloat()) * 0.7F + 1.0F) * 2.0F);
}
// drop remaining itemstack into the world
if (!remainder.isEmpty() && !world.isClientSide) {
ItemEntity entityitem = new ItemEntity(world, player.getX(), player.getY() + 0.5, player.getZ(), remainder);
entityitem.setPickUpDelay(40);
entityitem.setDeltaMovement(entityitem.getDeltaMovement().multiply(0, 1, 0));
world.addFreshEntity(entityitem);
}
}
Aggregations