Entité qui ramasse un item et qui l'ajoute à son inventaire



  • Bonjour, mon entitée a pour but de planter et casser des plantations, seul problème je n'ai pas trouvé comment ajouter ces items qui droppent à ses pieds à son inventaire, je me suis basé sur le code des Minecarts, si quelqu'un a une idée de la solution, les class de l'entitée :

    Classe de l'entitée :

    package fr.ciolgaming.magistry.entity;
    
    import java.util.Random;
    
    import fr.ciolgaming.magistry.entity.container.EntityFarmerContainer;
    import net.minecraft.block.BlockCrops;
    import net.minecraft.entity.Entity;
    import net.minecraft.entity.item.EntityItem;
    import net.minecraft.init.Blocks;
    import net.minecraft.inventory.InventoryBasic;
    import net.minecraft.inventory.InventoryLargeChest;
    import net.minecraft.item.Item;
    import net.minecraft.item.ItemStack;
    import net.minecraft.util.math.BlockPos;
    import net.minecraft.world.World;
    
    public class EntityFarmer extends EntityFarmerContainer{
    	
    	private int timer = 5;
    	private int timermove = 70;
    	
    //	private InventoryLargeChest inven;
    	
    	public EntityFarmer(World worldIn) {
    		super(worldIn);
    	}
    	
    	@Override
    	public void onLivingUpdate() {
    		super.onLivingUpdate();
    		if(timer == 5) {
    			setAIMoveSpeed(0F);
    			int x = getPosition().getX();
    			int y = getPosition().getY()-1;
    			int y1 = getPosition().getY();
    			int z = getPosition().getZ();
    			BlockPos posfarm = new BlockPos(x, y, z);
    			BlockPos pos = new BlockPos(x, y1, z);
    		    int[] xi = {-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2};
    		    int[] zi = {2,2,2,2,2,1,1,1,1,1,0,0,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2};
    		    int resultat = 0;
    		    for(int i=0; i < zi.length; i++) {
    		    	BlockPos poss = new BlockPos(x + xi[i], y, z + zi[i]);
    		    	BlockPos poss1 = new BlockPos(x + xi[i], y1, z + zi[i]);
    		    	if(getEntityWorld().getBlockState(poss).getBlock().equals(Blocks.FARMLAND)) {
    			    	if(!getEntityWorld().getBlockState(poss1).getBlock().equals(Blocks.WHEAT)) {
    			    		BlockPos poss2 = new BlockPos(x + xi[i], y1, z + zi[i]);
    			    	//	moveToBlockPosAndAngles(poss2, getPitchYaw().x, getPitchYaw().y);
    			    		Random rd = new Random();
    			    		motionX = motionX + (0.27+(rd.nextInt(5)*0.1))*xi[i];
    			    		motionZ = motionZ + (0.27+(rd.nextInt(5)*0.1))*zi[i];
    						timermove = 120;
    						setAIMoveSpeed(0F);
    			    	}
    			    //	if() {
    			    	if(getEntityWorld().getBlockState(poss1).getBlock().equals(Blocks.WHEAT)) {
    			    		if(getEntityWorld().getBlockState(poss1).getValue(BlockCrops.AGE).intValue() == 7) {
    			    			getEntityWorld().getBlockState(poss1).getBlock().dropBlockAsItem(getEntityWorld(), poss1, getEntityWorld().getBlockState(poss1), 0);
    			    			getEntityWorld().setBlockToAir(poss1);
    			    			getEntityWorld().setBlockState(pos, Blocks.WHEAT.getDefaultState());
    			    		}
    			    		//System.out.println(getEntityWorld().getBlockState(poss1).getValue(BlockCrops.AGE).intValue());
    			    	}
    			    //	}
    		    	}
    		    }
    			if(getEntityWorld().getBlockState(posfarm).getBlock().equals(Blocks.FARMLAND)) {
    				if(!getEntityWorld().getBlockState(pos).getBlock().equals(Blocks.WHEAT)) {
    					getEntityWorld().setBlockState(pos, Blocks.WHEAT.getDefaultState());
    				}
    			}
    			timer = 0;
    		//	getEntityWorld().setBlockState(pos, Blocks.OBSIDIAN.getDefaultState());
    			getEntityWorld().getBlockState(posfarm);
    			
    		}else {
    			timer++;
    		}
    		
    		if(timermove!=0) {
    			timermove--;
    		}else {
    			setAIMoveSpeed(0.2F);
    		}
    	}
    
    }
    

    Classe du container :

    package fr.ciolgaming.magistry.entity.container;
    
    import java.util.Random;
    
    import javax.annotation.Nullable;
    
    import fr.ciolgaming.magistry.entity.EntityBasicFarmer;
    import net.minecraft.entity.Entity;
    import net.minecraft.entity.SharedMonsterAttributes;
    import net.minecraft.entity.item.EntityMinecart;
    import net.minecraft.entity.player.EntityPlayer;
    import net.minecraft.entity.player.InventoryPlayer;
    import net.minecraft.inventory.Container;
    import net.minecraft.inventory.ContainerChest;
    import net.minecraft.inventory.InventoryHelper;
    import net.minecraft.inventory.ItemStackHelper;
    import net.minecraft.item.ItemStack;
    import net.minecraft.nbt.NBTTagCompound;
    import net.minecraft.util.EnumHand;
    import net.minecraft.util.NonNullList;
    import net.minecraft.util.ResourceLocation;
    import net.minecraft.util.datafix.DataFixer;
    import net.minecraft.util.datafix.FixTypes;
    import net.minecraft.util.datafix.walkers.ItemStackDataLists;
    import net.minecraft.world.ILockableContainer;
    import net.minecraft.world.LockCode;
    import net.minecraft.world.World;
    import net.minecraft.world.WorldServer;
    import net.minecraft.world.storage.loot.ILootContainer;
    import net.minecraft.world.storage.loot.LootContext;
    import net.minecraft.world.storage.loot.LootTable;
    
    public class EntityFarmerContainer extends EntityBasicFarmer implements ILockableContainer, ILootContainer
    {
        private NonNullList<ItemStack> minecartContainerItems = NonNullList.<ItemStack>withSize(9, ItemStack.EMPTY);
        /**
         * When set to true, the minecart will drop all items when setDead() is called. When false (such as when travelling
         * dimensions) it preserves its contents.
         */
        public boolean dropContentsWhenDead = true;
        private ResourceLocation lootTable;
        private long lootTableSeed;
    
        public EntityFarmerContainer(World worldIn)
        {
            super(worldIn);
        }
    
        public EntityFarmerContainer(World worldIn, double x, double y, double z)
        {
            super(worldIn);
        }
    
        public boolean isEmpty()
        {
            for (ItemStack itemstack : this.minecartContainerItems)
            {
                if (!itemstack.isEmpty())
                {
                    return false;
                }
            }
    
            return true;
        }
    
        /**
         * Returns the stack in the given slot.
         */
        public ItemStack getStackInSlot(int index)
        {
            this.addLoot((EntityPlayer)null);
            return this.minecartContainerItems.get(index);
        }
    
        /**
         * Removes up to a specified number of items from an inventory slot and returns them in a new stack.
         */
        public ItemStack decrStackSize(int index, int count)
        {
            this.addLoot((EntityPlayer)null);
            return ItemStackHelper.getAndSplit(this.minecartContainerItems, index, count);
        }
    
        /**
         * Removes a stack from the given slot and returns it.
         */
        public ItemStack removeStackFromSlot(int index)
        {
            this.addLoot((EntityPlayer)null);
            ItemStack itemstack = this.minecartContainerItems.get(index);
    
            if (itemstack.isEmpty())
            {
                return ItemStack.EMPTY;
            }
            else
            {
                this.minecartContainerItems.set(index, ItemStack.EMPTY);
                return itemstack;
            }
        }
    
        /**
         * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
         */
        public void setInventorySlotContents(int index, ItemStack stack)
        {
            this.addLoot((EntityPlayer)null);
            this.minecartContainerItems.set(index, stack);
    
            if (!stack.isEmpty() && stack.getCount() > this.getInventoryStackLimit())
            {
                stack.setCount(this.getInventoryStackLimit());
            }
        }
    
        /**
         * For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it
         * hasn't changed and skip it.
         */
        public void markDirty()
        {
        }
    
        /**
         * Don't rename this method to canInteractWith due to conflicts with Container
         */
        public boolean isUsableByPlayer(EntityPlayer player)
        {
            if (this.isDead)
            {
                return false;
            }
            else
            {
                return player.getDistanceSq(this) <= 64.0D;
            }
        }
    
        public void openInventory(EntityPlayer player)
        {
        }
    
        public void closeInventory(EntityPlayer player)
        {
        }
    
        /**
         * Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot. For
         * guis use Slot.isItemValid
         */
        public boolean isItemValidForSlot(int index, ItemStack stack)
        {
            return true;
        }
    
        /**
         * Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended.
         */
        public int getInventoryStackLimit()
        {
            return 64;
        }
    
        @Nullable
        public Entity changeDimension(int dimensionIn, net.minecraftforge.common.util.ITeleporter teleporter)
        {
            this.dropContentsWhenDead = false;
            return super.changeDimension(dimensionIn, teleporter);
        }
    
        /**
         * Will get destroyed next tick.
         */
        public void setDead()
        {
            if (this.dropContentsWhenDead)
            {
                InventoryHelper.dropInventoryItems(this.world, this, this);
            }
    
            super.setDead();
        }
    
        /**
         * Sets whether this entity should drop its items when setDead() is called. This applies to container minecarts.
         */
        public void setDropItemsWhenDead(boolean dropWhenDead)
        {
            this.dropContentsWhenDead = dropWhenDead;
        }
    
        public static void addDataFixers(DataFixer p_190574_0_, Class<?> p_190574_1_)
        {
            EntityMinecart.registerFixesMinecart(p_190574_0_, p_190574_1_);
            p_190574_0_.registerWalker(FixTypes.ENTITY, new ItemStackDataLists(p_190574_1_, new String[] {"Items"}));
        }
    
        /**
         * (abstract) Protected helper method to write subclass entity data to NBT.
         */
        public void writeEntityToNBT(NBTTagCompound compound)
        {
            super.writeEntityToNBT(compound);
    
            if (this.lootTable != null)
            {
                compound.setString("LootTable", this.lootTable.toString());
    
                if (this.lootTableSeed != 0L)
                {
                    compound.setLong("LootTableSeed", this.lootTableSeed);
                }
            }
            else
            {
                ItemStackHelper.saveAllItems(compound, this.minecartContainerItems);
            }
        }
    
        /**
         * (abstract) Protected helper method to read subclass entity data from NBT.
         */
        public void readEntityFromNBT(NBTTagCompound compound)
        {
            super.readEntityFromNBT(compound);
            this.minecartContainerItems = NonNullList.<ItemStack>withSize(this.getSizeInventory(), ItemStack.EMPTY);
    
            if (compound.hasKey("LootTable", 8))
            {
                this.lootTable = new ResourceLocation(compound.getString("LootTable"));
                this.lootTableSeed = compound.getLong("LootTableSeed");
            }
            else
            {
                ItemStackHelper.loadAllItems(compound, this.minecartContainerItems);
            }
        }
    
        public boolean processInteract(EntityPlayer player, EnumHand hand)
        {
        	ItemStack itemstack = player.getHeldItem(hand);
            if (!this.world.isRemote)
            {
                    player.displayGUIChest(this);
            }
    
            return true;
        }
        
    
        public void setTamed(boolean tamed)
        {
            super.setTamed(tamed);
    
            if (tamed)
            {
                this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(20.0D);
            }
            else
            {
                this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(8.0D);
            }
    
            this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(4.0D);
        }
    
        protected void applyDrag()
        {
            float f = 0.98F;
    
            if (this.lootTable == null)
            {
                int i = 15 - Container.calcRedstoneFromInventory(this);
                f += (float)i * 0.001F;
            }
    
            this.motionX *= (double)f;
            this.motionY *= 0.0D;
            this.motionZ *= (double)f;
        }
    
        public int getField(int id)
        {
            return 0;
        }
    
        public void setField(int id, int value)
        {
        }
    
        public int getFieldCount()
        {
            return 0;
        }
    
        public boolean isLocked()
        {
            return false;
        }
    
        public void setLockCode(LockCode code)
        {
        }
    
        public LockCode getLockCode()
        {
            return LockCode.EMPTY_CODE;
        }
    
        /**
         * Adds loot to the minecart's contents.
         */
        public void addLoot(@Nullable EntityPlayer player)
        {
            if (this.lootTable != null)
            {
                LootTable loottable = this.world.getLootTableManager().getLootTableFromLocation(this.lootTable);
                this.lootTable = null;
                Random random;
    
                if (this.lootTableSeed == 0L)
                {
                    random = new Random();
                }
                else
                {
                    random = new Random(this.lootTableSeed);
                }
    
                LootContext.Builder lootcontext$builder = new LootContext.Builder((WorldServer)this.world).withLootedEntity(this); // Forge: add looted entity to LootContext
    
                if (player != null)
                {
                    lootcontext$builder.withLuck(player.getLuck()).withPlayer(player); // Forge: add player to LootContext
                }
    
                loottable.fillInventory(this, random, lootcontext$builder.build());
            }
        }
    
        public net.minecraftforge.items.IItemHandler itemHandler = new net.minecraftforge.items.wrapper.InvWrapper(this);
    
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public <T> T getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.util.EnumFacing facing)
        {
            if (capability == net.minecraftforge.items.CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
            {
                return (T) itemHandler;
            }
            return super.getCapability(capability, facing);
        }
    
        @Override
        public boolean hasCapability(net.minecraftforge.common.capabilities.Capability<?> capability, @Nullable net.minecraft.util.EnumFacing facing)
        {
            return capability == net.minecraftforge.items.CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
        }
    
        public void clear()
        {
            this.addLoot((EntityPlayer)null);
            this.minecartContainerItems.clear();
        }
    
        public void setLootTable(ResourceLocation lootTableIn, long lootTableSeedIn)
        {
            this.lootTable = lootTableIn;
            this.lootTableSeed = lootTableSeedIn;
        }
    
        public ResourceLocation getLootTable()
        {
            return this.lootTable;
        }
    
    	@Override
    	public int getSizeInventory() {
    		// TODO Auto-generated method stub
    		return 9;
    	}
    
    	@Override
    	public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
            this.addLoot(playerIn);
            return new ContainerChest(playerInventory, this, playerIn);
    	}
    
    	@Override
    	public String getGuiID() {
            return "minecraft:chest";
    	}
    }
    

    et la class qui n'est pas très utile :

    package fr.ciolgaming.magistry.entity;
    
    import javax.annotation.Nullable;
    
    import com.google.common.base.Predicate;
    
    import net.minecraft.entity.Entity;
    import net.minecraft.entity.ai.EntityAIAttackMelee;
    import net.minecraft.entity.ai.EntityAIBeg;
    import net.minecraft.entity.ai.EntityAIFollowOwner;
    import net.minecraft.entity.ai.EntityAIHurtByTarget;
    import net.minecraft.entity.ai.EntityAILeapAtTarget;
    import net.minecraft.entity.ai.EntityAILookIdle;
    import net.minecraft.entity.ai.EntityAIMate;
    import net.minecraft.entity.ai.EntityAINearestAttackableTarget;
    import net.minecraft.entity.ai.EntityAIOwnerHurtByTarget;
    import net.minecraft.entity.ai.EntityAIOwnerHurtTarget;
    import net.minecraft.entity.ai.EntityAISit;
    import net.minecraft.entity.ai.EntityAISwimming;
    import net.minecraft.entity.ai.EntityAITargetNonTamed;
    import net.minecraft.entity.ai.EntityAITempt;
    import net.minecraft.entity.ai.EntityAIWanderAvoidWater;
    import net.minecraft.entity.ai.EntityAIWatchClosest;
    import net.minecraft.entity.monster.AbstractSkeleton;
    import net.minecraft.entity.passive.EntityAnimal;
    import net.minecraft.entity.passive.EntityLlama;
    import net.minecraft.entity.passive.EntityRabbit;
    import net.minecraft.entity.passive.EntitySheep;
    import net.minecraft.entity.passive.EntityWolf;
    import net.minecraft.entity.player.EntityPlayer;
    import net.minecraft.init.Items;
    import net.minecraft.world.World;
    
    public class EntityBasicBanker extends EntityWolf{
    
    	public EntityBasicBanker(World worldIn) {
    		super(worldIn);
    		setSize(0.75F, 2F);
    	}
    	
    	@Override
    	public float getEyeHeight() {
    		// TODO Auto-generated method stub
    		return 1.72F;
    	}
    
    }
    
    

    Merci de votre réponse et de vous interesser à ma question et je vous souhaite une agréable journée,

    Ciolgaming



  • Base toi sur le farmer villager, non ?



  • Ouais j'ai essayé mais je n'arrive pas à le faire de la même façon, j'ai la ligne de code qui permet de placer un item dans l'inventaire mais pas celle qui permet de récupérer les items au sol



  • Regarde du côté du hopper.



  • Ah ouiii j'avais pas pensé merci 🙂


Log in to reply