Jump to content

[1.8] Question about Slot


phlinther1

Recommended Posts

Hey guys!

 

I'm new to this forum, to forge and to Java generally, but I'd like to learn ;D I'm trying to "deactivate" an inventory slot, but it doesn't seem to work (probably because my code is completely wrong xD), but maybe you can help me. This is what I did:

 

class CustomSlot: (creating my own subclass and modifying some methods, just have a look ^^)

 

public class CustomSlot extends Slot {

public CustomSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {

	super(inventoryIn, index, xPosition, yPosition);
	// TODO Auto-generated constructor stub
}


@Override
public boolean isItemValid(ItemStack stack) {

	return false;

}

@Override
public boolean canBeHovered() {

	return false;
}

@Override
public boolean canTakeStack(EntityPlayer playerIn) {

	return false;
}
}

 

 

event:

 


        @SubscribeEvent
public void onOpenContainer(PlayerOpenContainerEvent event)
{
	if(event.entityPlayer.openContainer.inventoryItemStacks.get(0) != null)
	{
		if(event.entityPlayer.openContainer.getClass().equals(ContainerPlayer.class))
		{			
			ItemStack stack=(ItemStack)event.entityPlayer.openContainer.inventoryItemStacks.get(0);
			String itemCrafted = stack.getItem().getUnlocalizedName().substring(5);
			if(itemCrafted.equalsIgnoreCase("stick"))
			{
                                        
                                        // this is the part where I need help
					Slot slot=(Slot) event.entityPlayer.openContainer.inventorySlots.get(1); 
				CustomSlot cs = new CustomSlot(slot.inventory, slot.getSlotIndex(), slot.xDisplayPosition, slot.yDisplayPosition);
				event.entityPlayer.openContainer.inventorySlots.set(1, cs);

			}

		}
	}

}

 

 

I guess the new Slot is just in the list of slots, but it's not actually being applied or whatever you call it, is tgere a way of doing this? I'd really be grateful if someone could help me since I'm a beginner ;D

Link to comment
Share on other sites

That stick check is irrelevant, just ignore it, it was just for testing. I guess I'll check it by

if (.getItem.equals(Items.SOMETHING))

then, but that's not the point anyway. I do have basic knowledge of Java, but just theoretical. So I thought why not improve my skills and gather practical experience by having some fun with Minecraft mods.

 

So I guess you are unable to answer my core question? Or don't you want to answer it?

Link to comment
Share on other sites

Lemme hint some "basics"

 

1. When you have instance, you don't use class comparing.

event.entityPlayer.openContainer.getClass().equals(ContainerPlayer.class)

use

openContainer instanceof ContainerPlayer

 

2. As said - for items use "item == item2"

 

3. Back to issue.

Code (tho very messy) seems it should work. The only issue that can actually be there is slot "number".

I was digging in containers some time ago - have GOOD look at those slot "IDs" and "numbers" or whatever you call it.

You will notice that slot has actually TWO indexes. one is set for slot one for container. You might have messed them up - make sure to fix that if it's the issue.

To add more: those 2 "numbers" are "n" and "n+1" - one start from 0 other from 1. I don't really remember, just sayin it is there.

 

EDIT

Also, this is wild guess - remember that there are 2 containers - for client and for server.

Make sure event and replacing slot is called on both sides, or if not - send packet to do so.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

Thank you for your help, i managed to get the correct slot and used packets to synchronize server and client (which was indeed necessary as you guessed correctly). But if I replace the crafting output slot of the inventory I can't make it work again afterwards. I tried saving the original slot:

SlotCrafting craftingSlot =  (SlotCrafting) player.openContainer.inventorySlots.get(0);
// 0 is the crafting output slot (or whatever you call it) in case you don't know

then change it to my custom slot, but after setting it back to the original slot:

player.openContainer.inventorySlots.set(0, craftingSlot);

it won't work properly anymore which means it will result in some weird behavior if you craft something (you can take out the crafted item by drag and drop but the items in the crafting matrix won't be consumed / if you shift click, the items in the crafting matrix will be consumed, but the output will disappear). I sent a packet to the client already, so synchronization I believe isn't the problem. How can I make it work again? I'd be very grateful if you could help me another time ;D

 

 

Link to comment
Share on other sites

This issue is VERY specific and I doubt I (or anyone?) can directly help you.

You could setup github - would be much easier to test code.

 

As to issue, I will try.

 

1. While normal player (survival) will receive itemStack updates from server, a player in creative mode is allowed to update itemStack other way around.

What I mean in that is you are in creative mode - the server will treat you as one who dictates what itemStack should be, updates are bidirectional.

Why I mention this: In case of desynchronization, if you are in creative your client might be overriding changes done by server - you should test this stuff in survival.

 

2. ContainerPlayer is not just player's inventory. It's actuly three inventories: player's, grid and result.

If you are editing behaviour of Container you also have to update it's inventories.

 

Idk exactly what are you doing, but ever considered simply replacing whole crafting grid with your own and handle it on your own?

Might be nicely doable with PlayerOpenContainerEvent and GuiOpenEvent.

 

Post more code, might help.

 

EDIT

To expand point 2.:

3. Setting slot in index to different slot WILL break container, that's why I told you to "update" all changed stuff.

Notice this:

protected Slot addSlotToContainer(Slot slotIn)
    {
        slotIn.slotNumber = this.inventorySlots.size();
        this.inventorySlots.add(slotIn);
        this.inventoryItemStacks.add((Object)null);
        return slotIn;
    }

There is much digging to be done there.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

Idk exactly what are you doing, but ever considered simply replacing whole crafting grid with your own and handle it on your own?

 

That doesn't sound too bad, but I really don't know where to start, any tutorial suggestions or something like that?

Link to comment
Share on other sites

No. There are no tutorials for advanced stuff.

 

There are few ways to do it - each mor/less compatyblie with everything else.

It REALLY depends on what you need.

 

Right now I know that you want to replace slot in container - but WHY?

Depending on why, you can:

1. Repalce whole container with your own, and open whatever inventory you like in your own container. (makes you incompatybile with any mod that does same)

2. Replace crafting inventory inside container and utilize inventory methods to alter how they work.

3. Replace slots adn leave inventory. Do whatever you need using slots.

 

What, why and when?

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

The reason I want to do this is because I thought it might be a way to implement player-based crafting restrictions (that's why I checked for the item). I didn't think about the effect that changing the slot will break the container. I'd like to have this behavior: If you are not allowed to craft an item, you can't take it out of the crafting slot. What do you suggest I should do? As I said I'm new to forge which is why I'm not sure what's doable and what not.

Link to comment
Share on other sites

An FML both-sided event:

 

@SubscribeEvent
public void onCraft(ItemCraftedEvent event)
{
event.player - you can make per-player check.
event.crafting - this is ItemStack.
event.craftMatrix - this is the crafting slots inventory.
}

 

What can you do with it? Well - anything.

You can check player, you can make crafting result in multiple outputs (by putting more stacks into crafting grid itself as "leftover").

Only thing you cannot do is to replace result. That, sadly leaves you with only one option - to edit ItemStack itself.

You can manipulate all: item, meta and NBT of given ItemStack result.

Problem is - you can't really set it to e.g null.

What you can do... well, idk really. You could maybe create item "failed crafting" that would be output if player can't craft item. xD

maybe you can nullify it. Doesn't seem like you can tho.

 

EDIT

Or as suggested beafore - replace whole crafting. But for that  can't write code for you. Try something on your own. I can help later. (I alredy told you where to look).

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

I actually did something like that: I gave the player 0 dirt as output if he isn't allowed to craft the itemm It worked l, but I wasn't satisfied with the solution because I thought there must be a better way.

 

Unfortunately, this event is not cancelable (because it's fired when the item is taken out already) which makes everything a lot harder.

 

I'll try to replace the whole inventory gui with my own one, because what would also be great is to add some "cannot be crafted" message or something like that.

Link to comment
Share on other sites

Make a custom IRecipe and replace vanilla's IRecipe. In that IRecipe, you can make player-based crafting. Here is a tutorial by diesieben07 for player-based crafting recipes.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

Make a custom IRecipe and replace vanilla's IRecipe. In that IRecipe, you can make player-based crafting. Here is a tutorial by diesieben07 for player-based crafting recipes.

 

Thank you, but not quite what I'm looking for because this will just make the restricted recipes to just not show up. I'd like them to show up, but you should not be able to take the output out of the crafting slot which seems to be A LOT harder to do ^^

 

 

However, I've got the custom player inventory set up (I'll do the same with the crafting table later), but I need help again. I replaced the original inventory with my own one and added my custom slot as the output slot (which is usually SlotCrafting, mine is SlotCraftingCustom). PROBLEM: When I try to take something out it got this weird server-and-client-not-synchronized behavior which is why I guess I have to send a packet, but where and which one? Or is it another problem?

 

STRANGE THING: (look at my code) In class "KeyHandler" if I ask for the container which is open AFTER I opened my custom one, it will still say "ContainerPlayer" instead of "ContainerCustom" although I sent a packet. Why? Is it even my container which is being opened there, but if not, how can't it be mine?

 

I checked if it's actually my custom inventory which is opened by removing the little entity in the top right corner which is looking at the mouse pointer which did work. On the server side I just removed some slots which of course resulted in errors when something is being put in there. So it's definitely my custom inventory which is being shown ;D

 

Here is my code:

 

KeyHandler: (actually just KeyInputEvent)

 

public class KeyHandler {

@SubscribeEvent
public void onKeyInput(KeyInputEvent event) {

	if (!FMLClientHandler.instance().isGUIOpen(GuiChat.class)) {

		if (Minecraft.getMinecraft().gameSettings.keyBindInventory.isKeyDown()) {

			EntityPlayer player = FMLClientHandler.instance().getClient().thePlayer;

			if (player.openContainer instanceof ContainerCustom) {

				player.closeScreen();
				RecipeMod.network.sendToServer(new PacketCloseGui());

			} else {

				player.openGui(RecipeMod.instance, 0, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ);
				RecipeMod.network.sendToServer(new PacketOpenGui());
			}

		}

	}

}

 

 

GuiHandler:

 

public class GuiHandler implements IGuiHandler {

@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	if (ID == RecipeMod.GUI_CUSTOM_INV) 
		return new ContainerCustom(player.inventory, false, player);
	else
		return null;
}

@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	if (ID == RecipeMod.GUI_CUSTOM_INV)
		return new GuiCustomPlayerInventory(player, player.inventory, ExtendedPlayer.get(player).inventory);
	else
		return null;
}

}

 

 

ContainerCustom: (copy&paste from vanilla code, only changed the crafting output slot from "SlotCrafting" to "SlotCraftingCustom")

 

public class ContainerCustom extends Container {

/** The crafting matrix inventory. */
    public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2);
    public IInventory craftResult = new InventoryCraftResult();
    /** Determines if inventory manipulation should be handled. */
    public boolean isLocalWorld;
    private final EntityPlayer thePlayer;
    private static final String __OBFID = "CL_00001754";

    public ContainerCustom(final InventoryPlayer playerInventory, boolean localWorld, EntityPlayer player)
    {
        this.isLocalWorld = localWorld;
        this.thePlayer = player;
        this.addSlotToContainer(new SlotCraftingCustom(playerInventory.player, this.craftMatrix, this.craftResult, 0, 144, 36));
        int i;
        int j;

        for (i = 0; i < 2; ++i)
        {
            for (j = 0; j < 2; ++j)
            {
                this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
            }
        }

        for (i = 0; i < 4; ++i)
        {
            final int k = i;
            this.addSlotToContainer(new Slot(playerInventory, playerInventory.getSizeInventory() - 1 - i, 8, 8 + i * 18)
            {
                private static final String __OBFID = "CL_00001755";
                /**
                 * Returns the maximum stack size for a given slot (usually the same as getInventoryStackLimit(), but 1
                 * in the case of armor slots)
                 */
                public int getSlotStackLimit()
                {
                    return 1;
                }
                /**
                 * Check if the stack is a valid item for this slot. Always true beside for the armor slots.
                 */
                public boolean isItemValid(ItemStack stack)
                {
                    if (stack == null) return false;
                    return stack.getItem().isValidArmor(stack, k, thePlayer);
                }
                @SideOnly(Side.CLIENT)
                public String getSlotTexture()
                {
                    return ItemArmor.EMPTY_SLOT_NAMES[k];
                }
            });
        }

        for (i = 0; i < 3; ++i)
        {
            for (j = 0; j < 9; ++j)
            {
                this.addSlotToContainer(new Slot(playerInventory, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
            }
        }

        for (i = 0; i < 9; ++i)
        {
            this.addSlotToContainer(new Slot(playerInventory, i, 8 + i * 18, 142));
        }

        this.onCraftMatrixChanged(this.craftMatrix);
    }

    /**
     * Callback for when the crafting matrix is changed.
     */
    public void onCraftMatrixChanged(IInventory inventoryIn)
    {
        this.craftResult.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj));
    }

    /**
     * Called when the container is closed.
     */
    public void onContainerClosed(EntityPlayer playerIn)
    {
        super.onContainerClosed(playerIn);

        for (int i = 0; i < 4; ++i)
        {
            ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);

            if (itemstack != null)
            {
                playerIn.dropPlayerItemWithRandomChoice(itemstack, false);
            }
        }

        this.craftResult.setInventorySlotContents(0, (ItemStack)null);
    }

    public boolean canInteractWith(EntityPlayer playerIn)
    {
        return true;
    }

    /**
     * Take a stack from the specified inventory slot.
     */
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int index)
    {
        ItemStack itemstack = null;
        Slot slot = (Slot)this.inventorySlots.get(index);

        if (slot != null && slot.getHasStack())
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (index == 0)
            {
                if (!this.mergeItemStack(itemstack1, 9, 45, true))
                {
                    return null;
                }

                slot.onSlotChange(itemstack1, itemstack);
            }
            else if (index >= 1 && index < 5)
            {
                if (!this.mergeItemStack(itemstack1, 9, 45, false))
                {
                    return null;
                }
            }
            else if (index >= 5 && index < 9)
            {
                if (!this.mergeItemStack(itemstack1, 9, 45, false))
                {
                    return null;
                }
            }
            else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack())
            {
                int j = 5 + ((ItemArmor)itemstack.getItem()).armorType;

                if (!this.mergeItemStack(itemstack1, j, j + 1, false))
                {
                    return null;
                }
            }
            else if (index >= 9 && index < 36)
            {
                if (!this.mergeItemStack(itemstack1, 36, 45, false))
                {
                    return null;
                }
            }
            else if (index >= 36 && index < 45)
            {
                if (!this.mergeItemStack(itemstack1, 9, 36, false))
                {
                    return null;
                }
            }
            else if (!this.mergeItemStack(itemstack1, 9, 45, false))
            {
                return null;
            }

            if (itemstack1.stackSize == 0)
            {
                slot.putStack((ItemStack)null);
            }
            else
            {
                slot.onSlotChanged();
            }

            if (itemstack1.stackSize == itemstack.stackSize)
            {
                return null;
            }

            slot.onPickupFromSlot(playerIn, itemstack1);
        }

        return itemstack;
    }

    /**
     * Called to determine if the current slot is valid for the stack merging (double-click) code. The stack passed in
     * is null for the initial slot that was double-clicked.
     */
    public boolean canMergeSlot(ItemStack p_94530_1_, Slot p_94530_2_)
    {
        return p_94530_2_.inventory != this.craftResult && super.canMergeSlot(p_94530_1_, p_94530_2_);
    }

}

 

 

GuiCustomPlayerInventory: (copy&paste from vanilla code)

 

@SideOnly(Side.CLIENT)
public class GuiCustomPlayerInventory extends InventoryEffectRenderer {

/** The old x position of the mouse pointer */
    private float oldMouseX;
    /** The old y position of the mouse pointer */
    private float oldMouseY;

    public GuiCustomPlayerInventory(EntityPlayer p_i1094_1_)
    {
        super(p_i1094_1_.inventoryContainer);
        this.allowUserInput = true;
    }

    /**
     * Called from the main game loop to update the screen.
     */
    public void updateScreen()
    {
        if (this.mc.playerController.isInCreativeMode())
        {
            this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer));
        }

        this.updateActivePotionEffects();
    }

    /**
     * Adds the buttons (and other controls) to the screen in question.
     */
    public void initGui()
    {
        this.buttonList.clear();

        if (this.mc.playerController.isInCreativeMode())
        {
            this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer));
        }
        else
        {
            super.initGui();
        }
    }

    /**
     * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY
     */
    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
    {
        this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 86, 16, 4210752);
    }

    /**
     * Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks
     */
    public void drawScreen(int mouseX, int mouseY, float partialTicks)
    {
        super.drawScreen(mouseX, mouseY, partialTicks);
        this.oldMouseX = (float)mouseX;
        this.oldMouseY = (float)mouseY;
    }

    /**
     * Args : renderPartialTicks, mouseX, mouseY
     */
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
    {
        GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
        this.mc.getTextureManager().bindTexture(inventoryBackground);
        int k = this.guiLeft;
        int l = this.guiTop;
        this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
        drawEntityOnScreen(k + 51, l + 75, 30, (float)(k + 51) - this.oldMouseX, (float)(l + 75 - 50) - this.oldMouseY, this.mc.thePlayer);
    }

    /**
     * Draws the entity to the screen. Args: xPos, yPos, scale, mouseX, mouseY, entityLiving
     */
    public static void drawEntityOnScreen(int p_147046_0_, int p_147046_1_, int p_147046_2_, float p_147046_3_, float p_147046_4_, EntityLivingBase p_147046_5_)
    {
       /* GlStateManager.enableColorMaterial();
        GlStateManager.pushMatrix();
        GlStateManager.translate((float)p_147046_0_, (float)p_147046_1_, 50.0F);
        GlStateManager.scale((float)(-p_147046_2_), (float)p_147046_2_, (float)p_147046_2_);
        GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F);
        float f2 = p_147046_5_.renderYawOffset;
        float f3 = p_147046_5_.rotationYaw;
        float f4 = p_147046_5_.rotationPitch;
        float f5 = p_147046_5_.prevRotationYawHead;
        float f6 = p_147046_5_.rotationYawHead;
        GlStateManager.rotate(135.0F, 0.0F, 1.0F, 0.0F);
        RenderHelper.enableStandardItemLighting();
        GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F);
        GlStateManager.rotate(-((float)Math.atan((double)(p_147046_4_ / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F);
        p_147046_5_.renderYawOffset = (float)Math.atan((double)(p_147046_3_ / 40.0F)) * 20.0F;
        p_147046_5_.rotationYaw = (float)Math.atan((double)(p_147046_3_ / 40.0F)) * 40.0F;
        p_147046_5_.rotationPitch = -((float)Math.atan((double)(p_147046_4_ / 40.0F))) * 20.0F;
        p_147046_5_.rotationYawHead = p_147046_5_.rotationYaw;
        p_147046_5_.prevRotationYawHead = p_147046_5_.rotationYaw;
        GlStateManager.translate(0.0F, 0.0F, 0.0F);
        RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager();
        rendermanager.setPlayerViewY(180.0F);
        rendermanager.setRenderShadow(false);
        rendermanager.renderEntityWithPosYaw(p_147046_5_, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F);
        rendermanager.setRenderShadow(true);
        p_147046_5_.renderYawOffset = f2;
        p_147046_5_.rotationYaw = f3;
        p_147046_5_.rotationPitch = f4;
        p_147046_5_.prevRotationYawHead = f5;
        p_147046_5_.rotationYawHead = f6;
        GlStateManager.popMatrix();
        RenderHelper.disableStandardItemLighting();
        GlStateManager.disableRescaleNormal();
        GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
        GlStateManager.disableTexture2D();
        GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);*/
    }

    protected void actionPerformed(GuiButton button) throws IOException
    {
        if (button.id == 0)
        {
            this.mc.displayGuiScreen(new GuiAchievements(this, this.mc.thePlayer.getStatFileWriter()));
        }

        if (button.id == 1)
        {
            this.mc.displayGuiScreen(new GuiStats(this, this.mc.thePlayer.getStatFileWriter()));
        }
    }
}

 

 

SlotCraftingCustom:

 

public class SlotCraftingCustom extends SlotCrafting{

public SlotCraftingCustom(EntityPlayer player, InventoryCrafting craftingInventory, IInventory p_i45790_3_, int slotIndex, int xPosition, int yPosition) {
	super(player, craftingInventory, p_i45790_3_, slotIndex, xPosition, yPosition);
}

@Override
public boolean canTakeStack(EntityPlayer playerIn) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean canBeHovered() {
	// TODO Auto-generated method stub
	return false;
}

}

 

 

 

I'd be grateful if you could help me again!

[btw if my text was too confusing: I'm actually only asking for the place in my code where I have to send the packet to the client telling him that the crafting output slot (index 0) is my custom one with my custom behavior; I also appreciate any other comments on my code]

 

@Ernio your profile pic makes me freak out xD

Link to comment
Share on other sites

 public GuiCustomPlayerInventory(EntityPlayer p_i1094_1_)
    {
        super(p_i1094_1_.inventoryContainer);
        this.allowUserInput = true;
    }

You pass in the vanilla container as the player inventory. You need to either set

EntityPlayer#inventoryContainer

to your container, or pass an instance to the

super

with exactly the same data as the vanilla player inventory.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

If you want you can call me (check your msg box). That is only because I simply loathe the need of moving my fingers, or so called "writing", while explaining my point. :)

 

Anyway, my notes:

 

1. What your keyHandler code does:

* Open gui on client

* Open gui on server

Why I don't like this:

* You never know when server receives msg or even if. Unexpected stuff: server won't open container while your client would.

* Ofc - that will proobably never happen, but just saying, I don't like this :D

How it should look:

* You send packet to server "PacketOpenGui" - on server handler you use player.openGui.

#openGui(...) works pretty much like this:

- When called on client - calls only client method.

- When called on server - calls server method, if method will return valid container, it will send packet to client to open gui for it.

Note that you will only use this for containers.

 

2. You started using static guiIDs (RecipeMod.GUI_CUSTOM_INV), yet:

player.openGui(RecipeMod.instance, 0 // you use integer.

 

3. I don't think you need this check:

!FMLClientHandler.instance().isGUIOpen(GuiChat.class)

You MIGHT need this tho:

FMLClientHandler.instance().getClient().inGameHasFocus

 

4. Just something that hurts my eyes: (I remind that those are my notes)

new ContainerCustom(player.inventory, false, player)

Why do people pre-get and pass params? Just pass player :P

 

5. You might wanna use switch in future (in GuiHanlder).

 

6.

public boolean isLocalWorld;

Don't. No need for additional fields. you have very fine player.worldObj.isRemote.

 

7. You copied most of container code from vanilla - please CLEAN it up.

 

8.

new SlotCraftingCustom(playerInventory.player

Wtf? As mentioned - pass only player to constructor and use it - you are making sphagetti there.

 

9. Mentioned before:

public GuiCustomPlayerInventory(EntityPlayer p_i1094_1_)
    {
        super(p_i1094_1_.inventoryContainer);
        this.allowUserInput = true;
    }

Gui is opened on client, you need to make new container for it:

public GuiCustomPlayerInventory(EntityPlayer player)
    {
        super(new ContainerCustom(player));
        this.allowUserInput = true;
    }

 

10. Again - cleanup your code.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

Wow, what a nice answer!

 

To your points:

 

1. I didn't really know that the server would automatically send a packet to the client telling him to open the gui, so I did this, but now I know it better ;D

 

2. Yea, recognized that later and changed it already (it was even the wrong number xD)

 

3. You are right, I really don't need this check, changed it.

 

4. I changed it before posting, but then I thought: hm it's in vanilla code, it must be there for SOMETHING (although I could'nt find any use for it), and changed it back. Why is it even there?

 

5. okay I will ;D

 

6. same as 4.

 

7. done

 

8. haha don't know why I didn't recognize it yesterday, it's really super weird :D

 

9. same as 8., pretty obvious, but I just didn't see it...

 

Everything works perfectly now, this forum here is great (or is it just Ernio who is great?) ;D Now the same for the crafting table, I'll come back if I need help with it, but I guess it should be fine.

 

EDIT: Aaaand here I am again. I've got the custom crafting table set up, but what's the right way to open it? (I want to open it instead of the standard crafting table). I tried:

 

        @SubscribeEvent
public void onInteract(PlayerInteractEvent event)
{
	Block blockClicked = event.world.getBlockState(event.pos).getBlock();

	if(event.action == Action.RIGHT_CLICK_BLOCK && blockClicked == Blocks.crafting_table) {

		EntityPlayer player = event.entityPlayer;
		player.openGui(RecipeMod.instance, RecipeMod.GUI_CUSTOM_CRAFT, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ);

	}
}

 

 

but this will still open the standard one... however if I remove the check for the block type (if it's a crafting table which we clicked on), it will open my custom crafting table when I right click at any block.

Link to comment
Share on other sites

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



×
×
  • Create New...

Important Information

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