Jump to content

Recommended Posts

Posted (edited)

Hi,

i have a tank, that works perfekt, renderer shows right amount, it keeps the data when disconnected and connected again. Just one problem. When i harvest the tank, it will get into my inventory, but it will loose it's data. After replacing, all fluid is gone.

Here's the block class. Relevant code, that works on all my other tile entities is at the end of file.

 

package thewizardmod.fluids;

import java.util.ArrayList;

import javax.annotation.Nullable;

import com.google.common.collect.Lists;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
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.Util.CapabilityUtils;

public class BlockTank extends Block implements ITileEntityProvider{
	public BlockTank() {
		super(Material.GLASS);
		this.setCreativeTab(CreativeTabs.MISC);
	}

	@SideOnly(Side.CLIENT)
	public BlockRenderLayer getBlockLayer() {
		return BlockRenderLayer.TRANSLUCENT;
	}

	@Override
	public boolean isOpaqueCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public boolean isFullCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public EnumBlockRenderType getRenderType(IBlockState iBlockState) {
		return EnumBlockRenderType.MODEL;
	}

	@Override
	public boolean hasTileEntity() {
		return true;
	}


	private IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos) {
		return CapabilityUtils.getCapability(world.getTileEntity(pos), CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}

	@Override
	public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
		final IFluidHandler fluidHandler = getFluidHandler(worldIn, pos);

		if (fluidHandler != null) {
			if(heldItem != null)
			{
				// If the bucket is not empty or filled with liquid magic, we don't want it
				if (heldItem.getItem().equals(Items.BUCKET) || FluidUtil.getFluidContained(heldItem).isFluidEqual(new FluidStack(StartupCommon.fluidMagic, 1000)))
				{
					// Try fill/empty the held fluid container from the tank
					boolean success = FluidUtil.interactWithFluidHandler(heldItem, fluidHandler, playerIn);
					//If the held item is a fluid container, stop processing here so it doesn't try to place its contents
					return FluidUtil.getFluidHandler(heldItem) != null;
				}
			}
		}
		return false;
	}

	@Override
	public TileEntity createNewTileEntity(World worldIn, int meta) {
		return new TileEntityTank();
	}
	
	@Override
	public final ArrayList<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
		int meta = state.getBlock().getMetaFromState(state);
	  	ItemStack ret = new ItemStack(this, 1, meta);
	  	NBTTagCompound compound = new NBTTagCompound();
	  	TileEntityTank tileEntity = (TileEntityTank) world.getTileEntity(pos);
	  	NBTTagCompound tileEntityTag = new NBTTagCompound();
	  	tileEntity.writeToNBT(tileEntityTag);
	  	compound.setTag("BlockEntityTag", tileEntityTag);
	  	ret.setTagCompound(compound);
	  	return Lists.newArrayList(ret);
	}

	@Override
	public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player,	boolean willHarvest) {
	  	if (willHarvest) return true; 
	  	return super.removedByPlayer(state, world, pos, player, willHarvest);
	}

	@Override
	public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tileEntity, ItemStack tool) {
	  	super.harvestBlock(world, player, pos, state, tileEntity, tool);
	  	world.setBlockToAir(pos);
	}


}

 

Edited by Dustpuppy
Posted

Now the renderer is not working anymore.

Was working before perfekt. I've fighted this beast the half day to get it working.

 

Renderer Class

package thewizardmod.fluids;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;

import org.lwjgl.opengl.GL11;

import thewizardmod.Util.CapabilityUtils;

public class RendererTank extends TileEntitySpecialRenderer<TileEntityTank>{

	@Override
	public void renderTileEntityAt(TileEntityTank te, double x, double y, double z, float partialTicks, int destroyStage) {
		World world = Minecraft.getMinecraft().theWorld;
		
        final IFluidHandler fluidHandler = getFluidHandler(world, new BlockPos(te.getPos().getX(), te.getPos().getY(), te.getPos().getZ()));
        int capacity = fluidHandler.getTankProperties()[0].getCapacity();
        FluidStack fluid = fluidHandler.getTankProperties()[0].getContents();
        if (fluid != null)
        {
            GlStateManager.pushMatrix();
			GlStateManager.disableLighting();
			GlStateManager.disableCull();
            Tessellator tess = Tessellator.getInstance();
            VertexBuffer buffer = tess.getBuffer();

            buffer.setTranslation(x, y, z);

            bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
            TextureAtlasSprite still = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString());
            TextureAtlasSprite flow =  Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getFlowing().toString());

            double posY = 0.0625F + (0.9 * ((float) fluid.amount / (float) capacity));
            float[] color = {1, 0, 0.3f, 0.3f};

            float low = 0.0625F;
            float high = 0.0625F * 15;
            
            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F, high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F, high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,   high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,   high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, 1F/16F,  high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, 1F/16F,  high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.setTranslation(0, 0, 0);
            GlStateManager.popMatrix();
        }
	
	}
	
	private IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos) {
		return CapabilityUtils.getCapability(world.getTileEntity(pos), CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}

}

 

Posted

Block class

package thewizardmod.fluids;

import java.util.ArrayList;

import javax.annotation.Nullable;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
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.Util.CapabilityUtils;

import com.google.common.collect.Lists;

public class BlockTank extends Block{ //  implements ITileEntityProvider{
	public BlockTank() {
		super(Material.GLASS);
		this.setCreativeTab(CreativeTabs.MISC);
	}

	@SideOnly(Side.CLIENT)
	public BlockRenderLayer getBlockLayer() {
		return BlockRenderLayer.TRANSLUCENT;
	}

	@Override
	public boolean isOpaqueCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public boolean isFullCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public EnumBlockRenderType getRenderType(IBlockState iBlockState) {
		return EnumBlockRenderType.MODEL;
	}

	@Override
	public boolean hasTileEntity() {
		return true;
	}


	private IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos) {
		return CapabilityUtils.getCapability(world.getTileEntity(pos), CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}

	@Override
	public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
		final IFluidHandler fluidHandler = getFluidHandler(worldIn, pos);

		if (fluidHandler != null) {
			if(heldItem != null)
			{
				// If the bucket is not empty or filled with liquid magic, we don't want it
				if (heldItem.getItem().equals(Items.BUCKET) || FluidUtil.getFluidContained(heldItem).isFluidEqual(new FluidStack(StartupCommon.fluidMagic, 1000)))
				{
					// Try fill/empty the held fluid container from the tank
					boolean success = FluidUtil.interactWithFluidHandler(heldItem, fluidHandler, playerIn);
					//If the held item is a fluid container, stop processing here so it doesn't try to place its contents
					return FluidUtil.getFluidHandler(heldItem) != null;
				}
			}
		}
		return false;
	}
/*
	@Override
	public TileEntity createNewTileEntity(World worldIn, int meta) {
		return new TileEntityTank();
	}
*/
	
	@Override
	public boolean hasTileEntity(IBlockState state) {
		return true;
	}
	
	@Override
	public TileEntity createTileEntity(World world, IBlockState state) {
		return new TileEntityTank();
	}
	
	
	@Override
	public final ArrayList<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
		int meta = state.getBlock().getMetaFromState(state);
	  	ItemStack ret = new ItemStack(this, 1, meta);
	  	NBTTagCompound compound = new NBTTagCompound();
	  	TileEntityTank tileEntity = (TileEntityTank) world.getTileEntity(pos);
	  	NBTTagCompound tileEntityTag = new NBTTagCompound();
	  	tileEntity.writeToNBT(tileEntityTag);
	  	compound.setTag("BlockEntityTag", tileEntityTag);
	  	ret.setTagCompound(compound);
	  	return Lists.newArrayList(ret);
	}

	@Override
	public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player,	boolean willHarvest) {
	  	if (willHarvest) return true; 
	  	return super.removedByPlayer(state, world, pos, player, willHarvest);
	}

	@Override
	public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tileEntity, ItemStack tool) {
	  	super.harvestBlock(world, player, pos, state, tileEntity, tool);
	  	world.setBlockToAir(pos);
	}


}

 

This works, but the renderer is not working anymore now. The tank it self take the fluid and i can take it out with an empty bucket.

Posted (edited)

Ok, debugger and me are not best friends, but as i see, it will not get into it. Have a break point at the first line of ItemBlock.setTileEntityNBT and it will not stop

 

Edited by Dustpuppy
Posted

Ha! Changed in block class this

	@Override
	public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
			ItemStack stack) {
		super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
		if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag")) {
			NBTTagCompound tag = stack.getTagCompound().getCompoundTag("BlockEntityTag");
			worldIn.getTileEntity(pos).readFromNBT(tag);
			worldIn.getTileEntity(pos).markDirty();
		}
	}

 

And catched in the renderer class, that he will not render, if tileentity is null.

 

Now i got an error

 

 

[Client thread/ERROR]: Received invalid update packet for null tile entity at BlockPos{x=428, y=4, z=165} with data: {FluidName:"fluid_magic",Amount:2000,x:428,y:4,z:165,id:"thewizardmodTileEntityTank"}

 

This is strange. The tile entity is null, but he knows the amount of fluid in it.

 

Posted

Ok, here is everything, that has to do with the tank.

 

Block class

Spoiler

package thewizardmod.fluids;

import java.util.ArrayList;

import javax.annotation.Nullable;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
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.Util.CapabilityUtils;

import com.google.common.collect.Lists;

public class BlockTank extends Block{ //  implements ITileEntityProvider{
	public BlockTank() {
		super(Material.GLASS);
		this.setCreativeTab(CreativeTabs.MISC);
	}

	@SideOnly(Side.CLIENT)
	public BlockRenderLayer getBlockLayer() {
		return BlockRenderLayer.TRANSLUCENT;
	}

	@Override
	public boolean isOpaqueCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public boolean isFullCube(IBlockState iBlockState) {
		return false;
	}

	@Override
	public EnumBlockRenderType getRenderType(IBlockState iBlockState) {
		return EnumBlockRenderType.MODEL;
	}

	@Override
	public boolean hasTileEntity() {
		return true;
	}


	private IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos) {
		return CapabilityUtils.getCapability(world.getTileEntity(pos), CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}
	
	
	@Override
	public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
		final IFluidHandler fluidHandler = getFluidHandler(worldIn, pos);

		if (fluidHandler != null) {
			if(heldItem != null)
			{
				// If the bucket is not empty or filled with liquid magic, we don't want it
				if (heldItem.getItem().equals(Items.BUCKET) || FluidUtil.getFluidContained(heldItem).isFluidEqual(new FluidStack(StartupCommon.fluidMagic, 1000)))
				{
					// Try fill/empty the held fluid container from the tank
					boolean success = FluidUtil.interactWithFluidHandler(heldItem, fluidHandler, playerIn);
					//If the held item is a fluid container, stop processing here so it doesn't try to place its contents
					return FluidUtil.getFluidHandler(heldItem) != null;
				}
			}
		}
		return false;
	}

	@Override
	public boolean hasTileEntity(IBlockState state) {
		return true;
	}
	
	@Override
	public TileEntity createTileEntity(World world, IBlockState state) {
		return new TileEntityTank();
	}
	
	@Override
	public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
			ItemStack stack) {
		super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
		if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag")) {
			NBTTagCompound tag = stack.getTagCompound().getCompoundTag("BlockEntityTag");
			worldIn.getTileEntity(pos).readFromNBT(tag);
			worldIn.getTileEntity(pos).markDirty();
		}
	}

	
	@Override
	public final ArrayList<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
		int meta = state.getBlock().getMetaFromState(state);
	  	ItemStack ret = new ItemStack(this, 1, meta);
	  	NBTTagCompound compound = new NBTTagCompound();
	  	TileEntityTank tileEntity = (TileEntityTank) world.getTileEntity(pos);
	  	NBTTagCompound tileEntityTag = new NBTTagCompound();
	  	tileEntity.writeToNBT(tileEntityTag);
	  	compound.setTag("BlockEntityTag", tileEntityTag);
	  	ret.setTagCompound(compound);
	  	return Lists.newArrayList(ret);
	}

	@Override
	public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player,	boolean willHarvest) {
	  	if (willHarvest) return true; 
	  	return super.removedByPlayer(state, world, pos, player, willHarvest);
	}

	@Override
	public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tileEntity, ItemStack tool) {
	  	super.harvestBlock(world, player, pos, state, tileEntity, tool);
	  	world.setBlockToAir(pos);
	}


}

 

Tile entity

 

Spoiler

package thewizardmod.fluids;

import javax.annotation.Nullable;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.capability.TileFluidHandler;

public class TileEntityTank extends TileFluidHandler{
	
	public static final int CAPACITY = 10 * Fluid.BUCKET_VOLUME;

	public TileEntityTank() {
		tank = new FluidTankWithTile(this, CAPACITY);
	}

	@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());
	}

}

 

 

Renderer

Spoiler

package thewizardmod.fluids;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;

import org.lwjgl.opengl.GL11;

import thewizardmod.Util.CapabilityUtils;

public class RendererTank extends TileEntitySpecialRenderer<TileEntityTank>{

	@Override
	public void renderTileEntityAt(TileEntityTank te, double x, double y, double z, float partialTicks, int destroyStage) {
		World world = Minecraft.getMinecraft().theWorld;
		
        final IFluidHandler fluidHandler = getFluidHandler(world, new BlockPos(te.getPos().getX(), te.getPos().getY(), te.getPos().getZ()));
        if(fluidHandler != null)
        {
        int capacity = fluidHandler.getTankProperties()[0].getCapacity();
        FluidStack fluid = fluidHandler.getTankProperties()[0].getContents();
        if (fluid != null)
        {
            GlStateManager.pushMatrix();
			GlStateManager.disableLighting();
			GlStateManager.disableCull();
            Tessellator tess = Tessellator.getInstance();
            VertexBuffer buffer = tess.getBuffer();

            buffer.setTranslation(x, y, z);

            bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
            TextureAtlasSprite still = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString());
            TextureAtlasSprite flow =  Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getFlowing().toString());

            double posY = 0.0625F + (0.9 * ((float) fluid.amount / (float) capacity));
            float[] color = {1, 0, 0.3f, 0.3f};

            float low = 0.0625F;
            float high = 0.0625F * 15;
            
            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F, high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F, high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,   high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,   high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, 1F/16F,  high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( high, 1F/16F,  low).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    low).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, posY,    high).tex(still.getInterpolatedU( 4), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( high, 1F/16F,  high).tex(still.getInterpolatedU( 4), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            buffer.pos( low, 1F/16F,  low).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, 1F/16F,  high).tex(still.getInterpolatedU(12), still.getInterpolatedV(15)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    high).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            buffer.pos( low, posY,    low).tex(still.getInterpolatedU(12), still.getInterpolatedV( 1)).color(color[0], color[1], color[2], color[3]).endVertex();
            tess.draw();

            buffer.setTranslation(0, 0, 0);
            GlStateManager.popMatrix();
        }
        }
	
	}
	
	private IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos) {
		return CapabilityUtils.getCapability(world.getTileEntity(pos), CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}

}

 

 

Two utility classes i've taken from someone else

Spoiler

package thewizardmod.fluids;

import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidEvent.FluidDrainingEvent;
import net.minecraftforge.fluids.FluidEvent.FluidFillingEvent;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;

/**
 * An extension of {@link FluidTank} that sets the {@link FluidTank#tile} field, so {@link FluidDrainingEvent} and {@link FluidFillingEvent} are fired.
 *
 * @author Choonster
 */
public class FluidTankWithTile extends FluidTank {
	public FluidTankWithTile(TileEntity tileEntity, int capacity) {
		super(capacity);
		tile = tileEntity;
	}

	public FluidTankWithTile(TileEntity tileEntity, FluidStack stack, int capacity) {
		super(stack, capacity);
		tile = tileEntity;
	}

	public FluidTankWithTile(TileEntity tileEntity, Fluid fluid, int amount, int capacity) {
		super(fluid, amount, capacity);
		tile = tileEntity;
	}
}

package thewizardmod.fluids;

import javax.annotation.Nullable;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.capability.TileFluidHandler;

public class TileEntityTank extends TileFluidHandler{
	
	public static final int CAPACITY = 10 * Fluid.BUCKET_VOLUME;

	public TileEntityTank() {
		tank = new FluidTankWithTile(this, CAPACITY);
	}

	@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());
	}

}

 

 

Client proxy

Spoiler

package thewizardmod.fluids;

import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fml.client.registry.ClientRegistry;

public class StartupClientOnly
{
  public static void preInitClientOnly()
  {
	  registerFluid(StartupCommon.itemFluidPoison, StartupCommon.blockFluidPoison, "poison");
	  registerFluid(StartupCommon.itemFluidMagic, StartupCommon.blockFluidMagic, "magic");

  
	  final int DEFAULT_ITEM_SUBTYPE = 0;
	  ModelResourceLocation itemModelResourceLocation = new ModelResourceLocation("thewizardmod:tank", "inventory");
	  ModelLoader.setCustomModelResourceLocation(StartupCommon.itemBlockTank, DEFAULT_ITEM_SUBTYPE, itemModelResourceLocation);
	  
	  ClientRegistry.bindTileEntitySpecialRenderer(TileEntityTank.class, new RendererTank());

  }


  public static void initClientOnly()
  {
  }

  public static void postInitClientOnly()
  {
  }

  public static void registerFluid(Item item, BlockFluidClassic fluidBlock, String name){
	  
	  final ModelResourceLocation modelResourceLocation = new ModelResourceLocation(fluidBlock.getRegistryName(), name);

	  ModelBakery.registerItemVariants(item);
	  
	  ModelLoader.setCustomMeshDefinition(item, new ItemMeshDefinition() {

		@Override
		public ModelResourceLocation getModelLocation(ItemStack stack) {
			return modelResourceLocation;
		}
		  
	  });
	  
	  ModelLoader.setCustomStateMapper(fluidBlock, new StateMapperBase() {
			
			@Override
			protected ModelResourceLocation getModelResourceLocation(IBlockState state) {
				return modelResourceLocation;
			}
	  });
	  
  }
  
}

 

 

Common proxy

Spoiler

package thewizardmod.fluids;

import net.minecraft.item.ItemBlock;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import thewizardmod.TheWizardMod;

public class StartupCommon
{

	public static FluidPoison fluidPoison = new FluidPoison();
	public static BlockFluidPoison blockFluidPoison;
	public static ItemBlock itemFluidPoison;
	
	public static FluidMagic fluidMagic = new FluidMagic();
	public static BlockFluidMagic blockFluidMagic;
	public static ItemBlock itemFluidMagic;
	

	  public static BlockTank blockTank;
	  public static ItemBlock itemBlockTank;
	
	public static void preInitCommon()
	{
		FluidRegistry.registerFluid(fluidPoison);
		fluidPoison.setUnlocalizedName("twm_fluid_poison");
		
		blockFluidPoison = new BlockFluidPoison(fluidPoison);
		
		blockFluidPoison.setRegistryName("blockFluid");
		blockFluidPoison.setUnlocalizedName("twm_fluid_poison");
	    GameRegistry.register(blockFluidPoison);


		itemFluidPoison = new ItemBlock(blockFluidPoison);
		itemFluidPoison.setRegistryName(blockFluidPoison.getRegistryName());
	    GameRegistry.register(itemFluidPoison);
	    
	    FluidRegistry.addBucketForFluid(fluidPoison);

	    
		FluidRegistry.registerFluid(fluidMagic);
		fluidMagic.setUnlocalizedName("twm_fluid_magic");
		
		blockFluidMagic = new BlockFluidMagic(fluidMagic);
		
		blockFluidMagic.setRegistryName("blockFluidMagic");
		blockFluidMagic.setUnlocalizedName("twm_fluid_magic");
	    GameRegistry.register(blockFluidMagic);


		itemFluidMagic = new ItemBlock(blockFluidMagic);
		itemFluidMagic.setRegistryName(blockFluidMagic.getRegistryName());
	    GameRegistry.register(itemFluidMagic);
	    
	    FluidRegistry.addBucketForFluid(fluidMagic);

	    
	    
	    blockTank = (BlockTank)(new BlockTank().setUnlocalizedName("twm_tank"));
	    blockTank.setRegistryName("tank");
	    GameRegistry.register(blockTank);

	    itemBlockTank = new ItemBlock(blockTank);
	    itemBlockTank.setRegistryName(blockTank.getRegistryName());
	    GameRegistry.register(itemBlockTank);

	    GameRegistry.registerTileEntity(TileEntityTank.class, TheWizardMod.MODID + "TileEntityTank");

	}

	public static void initCommon()
	{
	}

	public static void postInitCommon()
	{
	}
}

 

 

Posted

I got it. Taken out the line that reads the tag. There the old position is used and at this position is no tiele entity anymore at this time. Just comment out the line and it works.

 

	@Override
	public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
			ItemStack stack) {
		super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
		if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag")) {
			NBTTagCompound tag = stack.getTagCompound().getCompoundTag("BlockEntityTag");
//			worldIn.getTileEntity(pos).readFromNBT(tag);
			worldIn.getTileEntity(pos).markDirty();
		}
	}

 

Posted
On 9/11/2017 at 5:53 AM, diesieben07 said:
  • Do not use ITileEntityProvider.
  • The version of hasTileEntity you are overriding is deprecated.
  • Please use @Override when you intend to override methods.
  • There is no point in using equals to compare Item instances, use ==.
  • Put a breakpoint in ItemBlock.setTileEntityNBT and use the debugger to see what's going on exactly when you place the block.

I just did a clean up to my mod, according to the quote I switched from ITileEntityProvider to hasTileEntity() and createTileEntity(World, IBlockState). I'm curious about why ITileEntityProvider becomes deprecated? QwQ

My mod: SimElectricity - High Voltages, Electrical Power Transmission & Distribution

https://github.com/RoyalAliceAcademyOfSciences/SimElectricity

Posted
6 hours ago, Rikka0_0 said:

I just did a clean up to my mod, according to the quote I switched from ITileEntityProvider to hasTileEntity() and createTileEntity(World, IBlockState). I'm curious about why ITileEntityProvider becomes deprecated? QwQ

Notice that ITileEntityProivder methods use metadata while the methods in the Block class (added by Forge) use IBlockState

  • Like 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

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.