Jump to content

Recommended Posts

Posted

I'm attempting to add some form of crafting screen to an entity I'm creating, but the slots are not working properly and while items  can be put in, they cannot be taken out. This is a link to a gif of the issue in game. I'm also putting in my container code and my entity class. I'm not entirely sure what the issue could be, but I'm thinking there's something wrong with my container code. The container code is mostly from my tileentity which actually works,  so I'm not entirely sure why it doesn't work with the entity itself.


import net.minecraft.entity.Entity;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.*;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.IWorldPosCallable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;

import javax.annotation.Nullable;


import static com.minecraft2.ModBlocks.CLAIRO_CONTAINER;

public class ClairoContainer extends Container {


    public static Entity entity;
    private PlayerEntity playerEntity;
    private IItemHandler playerInventory;
    public IItemHandler handler;
    public ClairoContainer(int windowId, World world, BlockPos pos, PlayerInventory playerInventory, PlayerEntity player, Entity entity) {
        super(CLAIRO_CONTAINER, windowId);
        this.entity = entity;

        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);

        entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h -> {
            addSlot(new SlotItemHandler(h, 0, 64, 24));
            this.handler = h;
            //minecraft2mod.logger.info("ENTITY HAS CAPABILITY");
        });
        layoutPlayerInventorySlots(10, 70);
    }

    @Override
    public boolean canInteractWith(PlayerEntity playerEntity) {
        return true;

    }

    private int addSlotRange(IItemHandler handler, int index, int x, int y, int amount, int dx) {
        for (int i = 0 ; i < amount ; i++) {
            addSlot(new SlotItemHandler(handler, index, x, y));
            x += dx;
            index++;
        }
        return index;
    }

    private int addSlotBox(IItemHandler handler, int index, int x, int y, int horAmount, int dx, int verAmount, int dy) {
        for (int j = 0 ; j < verAmount ; j++) {
            index = addSlotRange(handler, index, x, y, horAmount, dx);
            y += dy;
        }
        return index;
    }

    private void layoutPlayerInventorySlots(int leftCol, int topRow) {
        // Player inventory
        addSlotBox(playerInventory, 9, leftCol, topRow, 9, 18, 3, 18);

        // Hotbar
        topRow += 58;
        addSlotRange(playerInventory, 0, leftCol, topRow, 9, 18);
    }

    @Override
    public ItemStack transferStackInSlot(PlayerEntity playerIn, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.inventorySlots.get(index);
        if (slot != null && slot.getHasStack()) {
            ItemStack stack = slot.getStack();
            itemstack = stack.copy();
            if (index == 0) {
                if (!this.mergeItemStack(stack, 1, 37, true)) {
                    return ItemStack.EMPTY;
                }
                slot.onSlotChange(stack, itemstack);
            } else {
                if (stack.getItem() == Items.DIAMOND) {
                    if (!this.mergeItemStack(stack, 0, 1, false)) {
                        return ItemStack.EMPTY;
                    }
                } else if (index < 28) {
                    if (!this.mergeItemStack(stack, 28, 37, false)) {
                        return ItemStack.EMPTY;
                    }
                } else if (index < 37 && !this.mergeItemStack(stack, 1, 28, false)) {
                    return ItemStack.EMPTY;
                }
            }

            if (stack.isEmpty()) {
                slot.putStack(ItemStack.EMPTY);
            } else {
                slot.onSlotChanged();
            }

            if (stack.getCount() == itemstack.getCount()) {
                return ItemStack.EMPTY;
            }

            slot.onTake(playerIn, stack);
        }

        return itemstack;
    }


}

Entity Code:

import net.minecraft.entity.AgeableEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.goal.*;
import net.minecraft.entity.effect.LightningBoltEntity;
import net.minecraft.entity.passive.AnimalEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class Clairo extends AnimalEntity implements ITickableTileEntity, INamedContainerProvider {

    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);

    public ClairoContainer container;

    public Clairo(EntityType<? extends AnimalEntity> p_i48568_1_, World p_i48568_2_) {

        super(p_i48568_1_, p_i48568_2_);
    }

    @Nullable
    @Override
    public AgeableEntity createChild(AgeableEntity ageableEntity) {
        return null;
    }


    @Override
    public boolean processInteract(PlayerEntity p_184645_1_, Hand p_184645_2_) {

        if(!world.isRemote)
        {
            if(this instanceof INamedContainerProvider)
            {
                NetworkHooks.openGui((ServerPlayerEntity) p_184645_1_, (INamedContainerProvider) this.getEntity(), this.getPosition());
            }
            else {
                throw new IllegalStateException("Our named container provider is missing!");
            }

            return true;
        }


        return super.processInteract(p_184645_1_, p_184645_2_);
    }



    @Override
    public void onStruckByLightning(LightningBoltEntity p_70077_1_) {
        this.setGlowing(true);
    }

    @Override
    protected void registerGoals() {
        this.goalSelector.addGoal(0, new SwimGoal(this));
        this.goalSelector.addGoal(1, new PanicGoal(this, 0.4));
        this.goalSelector.addGoal(2, new OpenDoorGoal(this, true));
        this.goalSelector.addGoal(3, new LookAtGoal(this, PlayerEntity.class, 6.0f));
        this.goalSelector.addGoal(4, new WaterAvoidingRandomWalkingGoal(this, 1.0));

        super.registerGoals();
    }

    @Override
    protected void updateAITasks() {
        super.updateAITasks();
    }

    public Entity entitygetter()
    {
        return this;
    }

    @Override
    public void livingTick() {
        if(this.world.isRemote)
        {
            handler.ifPresent(h ->
            {
                if(h.getStackInSlot(0) != null )
                {
                }

            });

        }
        super.livingTick();
    }

    @Override
    protected void registerAttributes() {
        super.registerAttributes();
        this.getAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(20.0);
        this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.2);
        this.getAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(20.0);
        this.getAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(10.0);
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {

        container = new ClairoContainer(i, playerEntity.world, playerEntity.getPosition(), playerInventory, playerEntity, this.getEntity());
        

        return container;
    }

    @Override
    public ITextComponent getDisplayName() {
        return new StringTextComponent(getType().getRegistryName().getPath());
    }


    private IItemHandler createHandler() {

        return new ItemStackHandler(9)
        {
            @Override
            protected void onContentsChanged(int slot) {
                handler.ifPresent(h ->
                {
                    //h.insertItem(0, h.getStackInSlot(0), false);
                });
            }

        };

    }
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return this.handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>)h).deserializeNBT(invTag));
        super.read(tag);
    }

    @Override
    public void writeAdditional(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>)h).serializeNBT();
            tag.put("inv", compound);
        });
        super.writeAdditional(tag);
    }
}

Please keep  in mind that I've been throwing hail mary's at  this code for a long time now so a lot of the code in here might not make sense and could even possibly be working against me. 

Any help is appreciated, thank you.

Posted

The ITickableTileEntity I copied from my TileEntity code, only now do I actually read the name and realize it's for tile entities ?‍♂️. The position for the openGui was for a the container constructor but now I realize that the position isn't even used and so I've removed it. The getEntity I was using for some earlier debugging and has now been removed. I'm not entirely sure what a ScreenFactory is so I've added my Gui code and my client proxy.

Proxy:

public class ClientProxy implements IProxy {

    @Override
    public World getClientWorld()
    {
        return Minecraft.getInstance().world;
    }

    @Override
    public PlayerEntity getClientPlayer()
    {
        return Minecraft.getInstance().player;
    }
    @Override
    public void init() {
        ScreenManager.registerFactory(ModBlocks.FURNACEBLOCK_CONTAINER, furnaceBlockScreen::new);
        RenderingRegistry.registerEntityRenderingHandler(ModEntityTypes.clairo_entity.get(), ClairoEntityRender::new);
        ScreenManager.registerFactory(ModBlocks.CLAIRO_CONTAINER, ClairoScreen::new);
    }
}

Screen:


public class ClairoScreen extends ContainerScreen<ClairoContainer> {

    private ResourceLocation GUI = new ResourceLocation(minecraft2mod.MOD_ID, "textures/gui/clairo_gui.png");

    public ClairoScreen(ClairoContainer p_i51105_1_, PlayerInventory p_i51105_2_, ITextComponent p_i51105_3_) {
        super(p_i51105_1_, p_i51105_2_, p_i51105_3_);
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float v, int i, int i1) {
        GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F);
        this.minecraft.getTextureManager().bindTexture(GUI);
        int relX = (this.width - this.xSize) / 2;
        int relY = (this.height - this.ySize) / 2;
        this.blit(relX, relY, 0, 0, this.xSize, this.ySize);
    }

    @Override
    public void render(int mouseX, int mouseY, float partialTicks) {
        this.renderBackground();
        super.render(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
    }

    @Override
    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {

    }

Thank you for the help.

Posted
@SubscribeEvent
        public static void onContainerRegistry(final RegistryEvent.Register<ContainerType<?>> event) {
            event.getRegistry().register(IForgeContainerType.create((windowId, inv, data) -> {
                BlockPos pos = data.readBlockPos();
                return new furnaceBlockContainer(windowId, minecraft2mod.proxy.getClientWorld(), pos, inv, minecraft2mod.proxy.getClientPlayer());
            }).setRegistryName("furnaceblock"));

            event.getRegistry().register(IForgeContainerType.create((windowId, inv, data) ->
            {

                return new ClairoContainer(windowId, minecraft2mod.proxy.getClientWorld(),  inv, minecraft2mod.proxy.getClientPlayer(), ClairoContainer.entity);
            }).setRegistryName("clairo_entity"));
        }

I think this would be where I'm creating the ContainerType, it's in my main mod file and is being registered with my TileEntity Container.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); It says that '.get()' is deprecated since version 1.21.1 and has been marked for removal. How should I replace this line or section of code so it works? Or is there a way to fix it? Full Block of Code: IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();    // This is the line that's messed up... I don't know why modEventBus.addListener(this::commonSetup); MinecraftForge.EVENT_BUS.register(this);
    • Sorry to have bothered everyone.  I think I've figured it out: NbtUtils.snbtToStructure() will allow me to get the compound tag from a string I can load, and ItemStack.setTag() will allow me to write it to an item. Again, sorry to bother everyone -- it took a long time to work it out, it seems finding answers on the internet by googling isn't a viable way to get info so it took a lot of guessing, experimenting, and trial and error until I hit upon the path to a solution.
    • Hello, My modded forge server was working with no issues up until last night. The current issue is that the server crashes as soon as another player joins.   Steps I have already tried: Deleted these files: banned-ips.json, banned-players.json, ops.json, usercache.json, whitelist.json. Deleted all player files Deleted the chunk that player was in   Mods: Pixelmon 1.20.2, 9.2.10 Crash log: https://pastebin.com/qauuZLRE Latest Log: https://pastebin.com/TxCGS4sc Other issue I get when starting up the server: [LanServerPinger #1/WARN] [net.minecraft.client.server.LanServerPinger/]: LanServerPinger: Network is unreachable
    • I tried to reinstall the server multiple times but nothing worked and I keep getting the same error... I do have the correct java 21 installed or whatever it was. I couldn't find whats causing this problem as I tried a lot to reinstall the files again and again.
    • OK, what I need is to be able to take a JSON string, from a config file or data pack, and convert into NBT that can be applied to any arbitrary item (technically, item stack). This could easily be done in 1.12.2 using JsonToNBT.getTagFromJson(String data) like so: NBTFromJsonWrapper(String label, String data) { super(label, label); try { wrapped = JsonToNBT.getTagFromJson(data); } catch (NBTException e) { System.err.println("Exception reading json-nbt string: " + e.getMessage()); wrapped = new NBTTagCompound(); } } However, I can't seem to find a way to do this in newer version, specifically 1.19.4 (though once I'm done updating to that version I plan to be updating the latest 1.20 and 1.21 version). Alternately, of these NBT strings that resemble JSON but are not quite would be just as good, perhaps better: {ench:[{lvl:3s,id:35s},{lvl:5s,id:32s}],Unbreakable:1b,display:{Lore:["Believe it or not, this comes from ","an ancient Vanilla World. "],Name:"Fortuna Major"}} This was previously used for several purposes, one was simply to create purely vanilla potions.  The other was to create special items, primarily as trophies albeit practically useful trophies, often in the form of Easter Eggs. (I also had a homebrew system along side it, but I don't think I'll be updating it.) Any help would be appreciated.  Surely there is still a way to do this, and codecs do not seem to be the answer.  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.