use of net.minecraftforge.items.wrapper.PlayerMainInvWrapper 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(EntityPlayer player, @Nonnull ItemStack stack, int preferredSlot) {
IItemHandler inventory = new PlayerMainInvWrapper(player.inventory);
World world = player.world;
// try adding it into the inventory
ItemStack remainder = stack;
// insert into preferred slot first
if (preferredSlot >= 0) {
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(player, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
}
// drop remaining itemstack into the world
if (!remainder.isEmpty() && !world.isRemote) {
EntityItem entityitem = new EntityItem(world, player.posX, player.posY + 0.5, player.posZ, stack);
entityitem.setPickupDelay(40);
entityitem.motionX = 0;
entityitem.motionZ = 0;
world.spawnEntity(entityitem);
}
}
Aggregations