Jump to content

[1.10.2] 2 Problems with tile entity and container


Recommended Posts

Posted

Hi,

i have a custom made kind of furnance. The burning and tank stuff, everyting is working fine.

The problems i have are:

 

1. If there is an item (stone) in the output slot and i shift click a stone in player inventory, he puts the item into this output slot, ignoring isItemValid in the container slot and isItemValidForSlot in the tile entity.

 

2. If i use hoppers to insert and extract items, he will do it, as long as i don't open the gui. If the gui is open, the extraction will not be updated in the gui. The insert will. If i do any interaction then with the gui, the items will be extracted and the gui slot getting updated.

 

This is the tile entity class

Quote

package thewizardmod.extractor;

import javax.annotation.Nullable;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.inventory.SlotFurnaceFuel;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemHoe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.UniversalBucket;
import net.minecraftforge.fluids.capability.TileFluidHandler;

public class TileEntityExtractor extends TileFluidHandler implements ISidedInventory, ITickable{
	
	public static final int CAPACITY = 10 * Fluid.BUCKET_VOLUME + 1;
	
	
	public ItemStack itemStacks[] = new ItemStack[5];

	public IInventory inventory;
	
	public int coolDown;
	public int burntime;
	public int burntimeLeft;
	public int burntimeMax;
	
	private int bucketInputSlot = 0;
	private int bucketOutputSlot = 1;
	private int oreInputSlot = 2;
	private int stoneOutputSlot = 3;
	private int fuelInputSlot = 4;


    private static final int[] SLOTS_TOP = new int[] {0, 2, 4};
    private static final int[] SLOTS_BOTTOM = new int[] {1, 3};
    private static final int[] SLOTS_SIDES = new int[] {};

	public TileEntityExtractor() {
		tank = new FluidTankWithTile(this, CAPACITY);
		tank.setFluid(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 1));
		this.coolDown = 0;
		this.burntime = 0;
		this.burntimeLeft = 0;
		this.burntimeMax = 0;
	}

	
	
	@Override
	public NBTTagCompound getUpdateTag() {
		return writeToNBT(new NBTTagCompound());
	}

	@Nullable
	@Override
	public SPacketUpdateTileEntity getUpdatePacket() {
		return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag());
	}

	@Override
	public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
		readFromNBT(pkt.getNbtCompound());
	}

    public void readFromNBT(NBTTagCompound compound)
    {
        super.readFromNBT(compound);
        NBTTagList nbttaglist = compound.getTagList("Items", 10);
        this.itemStacks = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
            int j = nbttagcompound.getByte("Slot");

            if (j >= 0 && j < this.itemStacks.length)
            {
                this.itemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound);
            }
        }
        int amount = compound.getInteger("tankAmount");
        if(amount == 0)
        	amount = 1;
        tank.drainInternal(CAPACITY, true);
        tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, amount), true);

        this.coolDown = compound.getInteger("coolDown");
        this.burntime = compound.getInteger("burntime");
        this.burntimeLeft = compound.getInteger("burntimeLeft");
        this.burntimeMax = compound.getInteger("burntimeMax");
    }

    public NBTTagCompound writeToNBT(NBTTagCompound compound)
    {
        super.writeToNBT(compound);
        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.itemStacks.length; ++i)
        {
            if (this.itemStacks[i] != null)
            {
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                nbttagcompound.setByte("Slot", (byte)i);
                this.itemStacks[i].writeToNBT(nbttagcompound);
                nbttaglist.appendTag(nbttagcompound);
            }
        }

        compound.setTag("Items", nbttaglist);
        
        compound.setInteger("tankAmount", tank.getFluidAmount());

        compound.setInteger("coolDown", this.coolDown);
        compound.setInteger("burntime", this.burntime);
        compound.setInteger("burntimeLeft", this.burntimeLeft);
        compound.setInteger("burntimeMax", this.burntimeMax);

        return compound;
    }


	@Override
	public int getSizeInventory() {
		return this.itemStacks.length;
	}



	@Override
	@Nullable
	public ItemStack getStackInSlot(int index) {
		return this.itemStacks[index];
	}



	@Override
	@Nullable
	public ItemStack decrStackSize(int index, int count) {
		return ItemStackHelper.getAndSplit(this.itemStacks, index, count);
	}



	@Override
	@Nullable
	public ItemStack removeStackFromSlot(int index) {
		return ItemStackHelper.getAndRemove(this.itemStacks, index);
	}



	@Override
	public void setInventorySlotContents(int index, @Nullable ItemStack stack) {
        boolean flag = stack != null && stack.isItemEqual(this.itemStacks[index]) && ItemStack.areItemStackTagsEqual(stack, this.itemStacks[index]);
        this.itemStacks[index] = stack;

        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }

        if (!flag)
        {
            this.markDirty();
        }
	}



	@Override
	public int getInventoryStackLimit() {
		return 64;
	}



	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
        return this.worldObj.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
	}



	@Override
	public void openInventory(EntityPlayer player) {
	}



	@Override
	public void closeInventory(EntityPlayer player) {
	}



	@Override
	public boolean isItemValidForSlot(int index, ItemStack itemstack) {
        if (index == oreInputSlot)
        {
        	if(itemstack.getItem() == Item.getItemFromBlock(thewizardmod.ores.StartupCommon.shadowdustOre))
        		return true;
        }
        else if(index == bucketInputSlot)
        {
            if(itemstack != null)
            {
            	// Empty buckets are allowed
            	if(itemstack.getItem() == Items.BUCKET)
            	{
            		return true;
            	}
            }
        }
        else if(index == fuelInputSlot)
        {
            return isItemFuel(itemstack) || SlotFurnaceFuel.isBucket(itemstack) && (itemstack == null || itemstack.getItem() != Items.BUCKET);
        }
        return false;
	}




	@Override
	public void setField(int id, int value) {
	}



	@Override
	public int getFieldCount() {
		return 0;
	}

	@Override
	public int getField(int id) {
		return 0;
	}



	@Override
	public void clear() {
        for (int i = 0; i < this.itemStacks.length; ++i)
        {
            this.itemStacks[i] = null;
        }
	}



	@Override
	public String getName() {
        return "container.twm_tank.name";
	}



	@Override
	public boolean hasCustomName() {
		return false;
	}



	@Override
	public int[] getSlotsForFace(EnumFacing side) {
        return side == EnumFacing.DOWN ? SLOTS_BOTTOM : (side == EnumFacing.UP ? SLOTS_TOP : SLOTS_SIDES);
	}



	@Override
	public boolean canInsertItem(int index, ItemStack itemStackIn,
			EnumFacing direction) {
		return this.isItemValidForSlot(index, itemStackIn);
		}



	@Override
	public boolean canExtractItem(int index, ItemStack stack,
			EnumFacing direction) {
			return true;
	}



	@Override
	public void update() {
		ItemStack inputStack = getStackInSlot(bucketInputSlot);

        if(inputStack != null)
        {
        	// Empty buckets are allowed
        	if(inputStack.getItem() == Items.BUCKET)
        	{
    			if(tank.getFluidAmount() - 1000 > 0 && getStackInSlot(bucketOutputSlot) == null)
    			{
    				tank.drain(1000, true);
    				decrStackSize(bucketInputSlot, 1);
    				ItemStack bucket = UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, thewizardmod.fluids.StartupCommon.fluidMagic);
     		       	setInventorySlotContents(bucketOutputSlot, bucket);
     		        markDirty();
    			}
        	}
        }
        
        ItemStack oreInputStack = getStackInSlot(oreInputSlot);

        if(oreInputStack != null)
        {
        	if(burntimeMax > 0)
        	{
        		this.coolDown++;
        		// It takes 2 second(40 ticks) to extract liquid magic from ore
        		if(this.coolDown >= 40)
        		{
    				coolDown = 40;
        			// We need 10 Ore to get a full bucket (1000mB)
        			if(tank.getFluidAmount() + 100 <= tank.getCapacity())
        			{
        				if(itemStacks[stoneOutputSlot] != null)
 		       			{	
        					if(itemStacks[stoneOutputSlot].stackSize < getInventoryStackLimit())
        					{
 		    	   				itemStacks[stoneOutputSlot].stackSize++;
 		        				tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 100), true);
 		        				decrStackSize(oreInputSlot, 1);
 		        				this.coolDown = 0;
        					}
 		       			}
 		       			else
 		       			{
 		       				itemStacks[stoneOutputSlot] = new ItemStack(Blocks.STONE);
 	        				tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 100), true);
 	        				decrStackSize(oreInputSlot, 1);
 	        				this.coolDown = 0;
 		       			}
 		       			setInventorySlotContents(stoneOutputSlot, itemStacks[stoneOutputSlot]);
 		       			markDirty();
        			}
        		}
        	}
        }
        else
        {
        	coolDown = 0;
            markDirty();
        }
        
        // Nothing burning
        if(this.burntimeMax == 0)
        {
        	ItemStack oreStack = getStackInSlot(oreInputSlot);
        	ItemStack fuelInputStack = getStackInSlot(fuelInputSlot);
        	if(fuelInputStack != null && oreStack != null)
        	{
        		if(tank.getFluidAmount() < tank.getCapacity())
        		{
        			if(itemStacks[stoneOutputSlot] != null)
        			{
        				if(itemStacks[stoneOutputSlot].stackSize < getInventoryStackLimit())
        				{
        					burntimeMax = getItemBurnTime(fuelInputStack);
        					if(burntimeMax > 0)
        					{
        						decrStackSize(fuelInputSlot, 1);
        						markDirty();
        					}
        				}
        			}
        			else
        			{
        				burntimeMax = getItemBurnTime(fuelInputStack);
        				if(burntimeMax > 0)
        				{
        					decrStackSize(fuelInputSlot, 1);
        					markDirty();
        				}
        			}
        		}
        	}
        }
        
        // burn fuel
        if(this.burntime < burntimeMax)
        {
        	burntime++;
            markDirty();
        }
        else
        {
        	burntime = 0;
        	burntimeMax = 0;
            markDirty();
        }
        markDirty();
	}

    public static int getItemBurnTime(ItemStack stack)
    {
        if (stack == null)
        {
            return 0;
        }
        else
        {
            Item item = stack.getItem();

            if (item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.AIR)
            {
                Block block = Block.getBlockFromItem(item);

                if (block == Blocks.WOODEN_SLAB)
                {
                    return 150;
                }

                if (block.getDefaultState().getMaterial() == Material.WOOD)
                {
                    return 300;
                }

                if (block == Blocks.COAL_BLOCK)
                {
                    return 16000;
                }
            }

            if (item instanceof ItemTool && "WOOD".equals(((ItemTool)item).getToolMaterialName())) return 200;
            if (item instanceof ItemSword && "WOOD".equals(((ItemSword)item).getToolMaterialName())) return 200;
            if (item instanceof ItemHoe && "WOOD".equals(((ItemHoe)item).getMaterialName())) return 200;
            if (item == Items.STICK) return 100;
            if (item == Items.COAL) return 1600;
            if (item == Items.LAVA_BUCKET) return 20000;
            if (item == Item.getItemFromBlock(Blocks.SAPLING)) return 100;
            if (item == Items.BLAZE_ROD) return 2400;
            return net.minecraftforge.fml.common.registry.GameRegistry.getFuelValue(stack);
        }
    }

    public static boolean isItemFuel(ItemStack stack)
    {
        return getItemBurnTime(stack) > 0;
    }


}

And this is the container

Quote

package thewizardmod.extractor;


import javax.annotation.Nullable;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import thewizardmod.ores.StartupCommon;
 
public class ContainerExtractor extends Container {
 
    public final TileEntityExtractor tileTank;

    public ContainerExtractor(InventoryPlayer playerInventory, TileEntityExtractor te)
    {
        this.tileTank = te;
        this.addSlotToContainer(new InputSlot(tileTank, 0, 26, 19));
        this.addSlotToContainer(new OutputSlot(tileTank, 1, 26, 55));
        this.addSlotToContainer(new OreInputSlot(tileTank, 2, 80, 19));
        this.addSlotToContainer(new StoneOutputSlot(tileTank, 3, 134, 19));
        this.addSlotToContainer(new FuelInputSlot(tileTank, 4, 80, 54));

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

        for (int k = 0; k < 9; ++k)
        {
            this.addSlotToContainer(new Slot(playerInventory, k, 8 + k * 18, 142));
        }
    }
    /**
     * Determines whether supplied player can use this container
     */
    public boolean canInteractWith(EntityPlayer playerIn)
    {
        return this.tileTank.isUseableByPlayer(playerIn);
    }

    /**
     * Take a stack from the specified inventory slot.
     */
    @Nullable
    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 < 5) {
                if (!this.mergeItemStack(itemstack1, 5, this.inventorySlots.size(), true)) {
                    return null;
                }
            }
            else if(index != 1 && index != 3) 
            {
            	if(!this.mergeItemStack(itemstack1, 0, 5, false)) 
            	{
            		return null;
            	}
            }
 
            if (itemstack1.stackSize == 0) {
                slot.putStack((ItemStack)null);
            }
            else {
                slot.onSlotChanged();
            }
        }
 
        return itemstack;
    }
    
	public class InputSlot extends Slot {

	    public InputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	// Empty buckets are allowed
            	if(itemstack.getItem() == Items.BUCKET)
            	{
            		return true;
            	}
            }
            
            return false;
		}
	}

	public class OutputSlot extends Slot {

	    public OutputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            return false;
		}
		
		
	}

	public class OreInputSlot extends Slot {

	    public OreInputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	if(itemstack.getItem() == Item.getItemFromBlock(StartupCommon.shadowdustOre))
            	{
            		return true;
            	}
            }
            
            return false;
		}
	}

	public class StoneOutputSlot extends Slot {

	    public StoneOutputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            return false;
		}
	}

	public class FuelInputSlot extends Slot {

	    public FuelInputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	return tileTank.isItemFuel(itemstack);
            }
            
            return false;
		}
	}


}

 

 

Posted

If needed, this is the gui

Quote

package thewizardmod.extractor;

import java.awt.Color;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import thewizardmod.Gui.ProgressBar;
import thewizardmod.Gui.ProgressBar.ProgressBarDirection;
import thewizardmod.Util.CapabilityUtils;

@SideOnly(Side.CLIENT)
public class GuiExtractor extends GuiContainer {
	private ProgressBar TankGauge;
	private ProgressBar progressBar;
	private ProgressBar burnBar;
	
	// This is the resource location for the background image for the GUI
	private static final ResourceLocation texture = new ResourceLocation("thewizardmod", "textures/gui/extractor_bg.png");
	private TileEntityExtractor tileEntityTank;

	public GuiExtractor(InventoryPlayer invPlayer, TileEntityExtractor tile) {
		super(new ContainerExtractor(invPlayer, tile));
		tileEntityTank = tile;
		this.TankGauge = new ProgressBar(texture, ProgressBarDirection.DOWN_TO_UP, 10, 62, 9, 9, 176, 14);
		this.progressBar = new ProgressBar(texture, ProgressBarDirection.LEFT_TO_RIGHT, 35, 17, 98, 18, 195, 0);
		this.burnBar = new ProgressBar(texture, ProgressBarDirection.DOWN_TO_UP, 14, 14, 81, 39, 195, 20);
	}

	// draw the background for the GUI - rendered first
	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int x, int y) {
		// Bind the image texture of our custom container
		Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
		// Draw the image
		GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
		drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
	}

	// draw the foreground for the GUI - rendered after the slots, but before the dragged items and tooltips
	// renders relative to the top left corner of the background
	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
		fontRendererObj.drawString("Liquid Magic Extractor", 50, 5, Color.darkGray.getRGB());
		final IFluidHandler fluidHandler = getFluidHandler();
		if (fluidHandler != null) {
	        FluidStack fluid = fluidHandler.getTankProperties()[0].getContents();
	        if (fluid != null)
	        {
	    		this.TankGauge.setMin(fluid.amount - 1).setMax(fluidHandler.getTankProperties()[0].getCapacity() - 1);
	    		this.TankGauge.draw(this.mc);
	    		
	    		this.progressBar.setMin(tileEntityTank.coolDown).setMax(40);
	    		this.progressBar.draw(this.mc);
	    		
	    		this.burnBar.setMin(tileEntityTank.burntimeMax - tileEntityTank.burntime).setMax(tileEntityTank.burntimeMax);
	    		this.burnBar.draw(this.mc);
	        }
		}
	}
	
	private IFluidHandler getFluidHandler() {
		return CapabilityUtils.getCapability(tileEntityTank, CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}
	
	

}

 

 

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

    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
  • Topics

×
×
  • Create New...

Important Information

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