Jump to content

Recommended Posts

Posted

hey guys this is my first time posting on these forums so i dont really know how things work so bare with me if there is some bbcode messups

so basically i made a windmill and this windmill works Almost Perfect the only issue is when i go into the game it doesn't save its power's progress bar, it saves the power but not the progress bar here is my tileentity and gui code

the main thing you want to look at is the "getpowerscaled" method in both classes

 

TileEntity

 

 package Mine_EE_GUI;

import Mine_EE.Mine_EE;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

public class TileEntityTurbine extends TileEntity implements IInventory {
public float power;
public float MAX;
public float LOW;

public static float display;
private ItemStack[] inventory;

public TileEntityTurbine() {
inventory = new ItemStack[2];
MAX = 1000;
LOW = 0;
}



private int item;



public void updateEntity()
{
if(this.power > MAX){
power = MAX;
}
}


public int GetPowerScaled(int scale) {
return (int) (this.power * scale / this.MAX);
}

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

@Override
public ItemStack getStackInSlot(int i) {
return inventory[i];
}


@Override
public ItemStack decrStackSize(int slot, int count) {
ItemStack itemstack = getStackInSlot(slot);


if(itemstack != null) 
{

if(itemstack.stackSize <= count) {
setInventorySlotContents(slot, null);
} else {
itemstack = itemstack.splitStack(count);
onInventoryChanged();
}
}
return itemstack;
}



@Override
public ItemStack getStackInSlotOnClosing(int slot) {
ItemStack itemstack = getStackInSlot(slot);

setInventorySlotContents(slot, null);
return itemstack;
}

@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
inventory[slot] = itemstack;

this.recipes(slot, itemstack);

if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) {
itemstack.stackSize = getInventoryStackLimit();
}
onInventoryChanged();
}


private void recipes(int slot, ItemStack itemstack) 
{
inventory[slot] = itemstack;


ItemStack stack = getStackInSlot(0); 

if(power < MAX){

if(stack != null && stack.itemID == Item.redstone.itemID && power < MAX)
{

this.removestack(slot,itemstack);
this.addpower(2 * stack.stackSize);
onInventoryChanged();

}

}
else if(power == MAX)
{

}
this.updateEntity();
}

private void removestack(int slot, ItemStack itemstack) 
{

setInventorySlotContents(0, null);
this.updateEntity();
}




public void addpower(int mpw) {

power = this.power + mpw;
if(this.power <= 0)
{
power = LOW;
}
if(this.power >= MAX)
{
power = MAX;
}
this.updateEntity();
}

@Override
public String getInvName() {
return "Again a Test Gui";
}

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

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

@Override
public boolean isUseableByPlayer(EntityPlayer player) {
if(player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64) {
return true;
} else {
return false;
}
}

@Override
public void openChest() {
}

@Override
public void closeChest() {
}

@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return false;
}


@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);

if(this.power > this.MAX) this.power = this.MAX;
compound.setFloat("power", this.power);


NBTTagList list = new NBTTagList();

for(int i = 0; i < getSizeInventory(); i++) {
ItemStack itemstack = getStackInSlot(i);

if(itemstack != null) {
NBTTagCompound item = new NBTTagCompound();

item.setByte("SlotDeployer", (byte) i);
itemstack.writeToNBT(item);
list.appendTag(item);
}
}

compound.setTag("ItemsDeployer", list);
}

@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
if(this.power < 0) this.power = 0;
this.power = compound.getFloat("power");

NBTTagList list = compound.getTagList("ItemsDeployer");

for(int i = 0; i < list.tagCount(); i++) {
NBTTagCompound item = (NBTTagCompound) list.tagAt(i);
int slot = item.getByte("SlotDeployer");

if(slot >= 0 && slot < getSizeInventory()) {
setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(item));
}
this.updateEntity();
}
}




}

[/i]

 

 

GUI

 

 package Mine_EE_GUI;

import org.lwjgl.opengl.GL11;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import Mine_EE.*;
import Mine_EE_GUI.*;
import NukesMods.ModThing.Extractor.TileEntityExtractor;

public class GuiTurbine extends GuiContainer 
{


public static final ResourceLocation texture = new ResourceLocation(Mine_EE.modid.toLowerCase(), "textures/gui/Turbine.png");

private TileEntityTurbine Turbine;
public GuiTurbine(InventoryPlayer invPlayer, TileEntityTurbine tile_entity) {
super(new ContainerTurbine(invPlayer, tile_entity));

this.Turbine = tile_entity;
xSize = 176;
ySize = 165;

}

protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
// this.fontRenderer.drawString(StatCollector.translateToLocal(Turbine.display + " MPW"), 103, 5, 0x404040);
}

@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j) {
GL11.glColor4f(1F, 1F, 1F, 1F);
this.mc.getTextureManager().bindTexture(texture);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);

int draw = this.Turbine.GetPowerScaled(40);

drawTexturedModalRect(guiLeft +83, guiTop+19+40-draw, 177, 40 - draw, 12, draw);

}

}

 

the bar works but when i leave the game and reopen it it doesn't save the state

Its best to only ask questions when you did most of the work yourself.

Posted

That's because you never write to NBT and read from NBT. So override the methods

public void writeToNBT(NBTTagCompound);

and

public void readFromNBT(NBTTagCompound);

. In those method you want to write and read your values from the NBTTagCompound passed in. Be sure to call the super methods!

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/

Posted

That's because you never write to NBT and read from NBT. So override the methods

public void writeToNBT(NBTTagCompound);

and

public void readFromNBT(NBTTagCompound);

. In those method you want to write and read your values from the NBTTagCompound passed in. Be sure to call the super methods!

 

I already have the writenbt and readnbt methods in my TileEntity class and it works fine the power saves,the items in the slots save but the bar doesn't save

Its best to only ask questions when you did most of the work yourself.

Posted

I think your problem is with the MAX value. You either need to save it using NBT, or don't initialize it in the constructor but directly when the field is made.

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/

Posted

I think your problem is with the MAX value. You either need to save it using NBT, or don't initialize it in the constructor but directly when the field is made.

i removed the max and low floats entirely and changed them with there numbers and it still wont save the bar

here is a image in game when i fill up the turbine with power

 

 

and here is a image of the same exact turbine when i reload the world

 

 

note that in chat the power is printed out as mpw's

Its best to only ask questions when you did most of the work yourself.

Posted

From where do you call the addPower method? I think your client and server are desynchronized.

i add power from recipes and i call recipes from getstackinslot oh and what may be usefull is my block code

 

 

 

package Mine_EE_GUI;

import java.util.List;
import java.util.Random;

import Mine_EE.Mine_EE;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Icon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.FMLNetworkHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class Turbine extends BlockContainer {
public Turbine(int id) {
	super(id, Material.iron);
	setCreativeTab(Mine_EE.ModTab2);
	this.setTickRandomly(true);
}

@Override
public TileEntity createNewTileEntity(World world) {
	return new TileEntityTurbine();

}

@Override
    public void breakBlock(World world, int x, int y, int z, int par5, int par6) {
            dropItems(world, x, y, z);
            super.breakBlock(world, x, y, z, par5, par6);
    }

  private void dropItems(World world, int x, int y, int z){
          Random rand = new Random();

          TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
          if (!(tileEntity instanceof IInventory)) {
                  return;
          }
          IInventory inventory = (IInventory) tileEntity;

          for (int i = 0; i < inventory.getSizeInventory(); i++) {
                  ItemStack item = inventory.getStackInSlot(i);

                  if (item != null && item.stackSize > 0) {
                          float rx = rand.nextFloat() * 0.8F + 0.1F;
                          float ry = rand.nextFloat() * 0.8F + 0.1F;
                          float rz = rand.nextFloat() * 0.8F + 0.1F;

                          EntityItem entityItem = new EntityItem(world,
                                          x + rx, y + ry, z + rz,
                                          new ItemStack(item.itemID, item.stackSize, item.getItemDamage()));

                          if (item.hasTagCompound()) {
                                  entityItem.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy());
                          }

                          float factor = 0.05F;
                          entityItem.motionX = rand.nextGaussian() * factor;
                          entityItem.motionY = rand.nextGaussian() * factor + 0.2F;
                          entityItem.motionZ = rand.nextGaussian() * factor;
                          world.spawnEntityInWorld(entityItem);
                          item.stackSize = 0;
                  }
          }
  }
	 public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
	    {
	        float f = 0.01F;
	        return AxisAlignedBB.getAABBPool().getAABB((double)par2, (double)par3, (double)par4, (double)(par2 + 1), (double)((float)(par3 + 1) - f), (double)(par4 + 1));
	    }
  
  public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
	{

	}
  
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) {
	 ItemStack itemstack = player.inventory.getCurrentItem();
	 TileEntityTurbine t = (TileEntityTurbine) world.getBlockTileEntity(x, y, z);


	 if(!world.isRemote && player.isSneaking()) 
		{
			player.addChatMessage(t.power + " MPW");
		}

	 if(!world.isRemote && !player.isSneaking()) 
		{
			FMLNetworkHandler.openGui(player, Mine_EE.instance, 54, world, x, y, z);
		}
	 t.updateEntity();
	return true;
}

@Override
public void onBlockAdded(World world, int x, int y, int z) {
	super.onBlockAdded(world, x, y, z);
	setDefaultDirection(world, x, y, z);

		}



@SideOnly(Side.CLIENT)
public static Icon topIcon;
@SideOnly(Side.CLIENT)
public static Icon sideIcon;
@SideOnly(Side.CLIENT)
public static Icon frontIcon;
@SideOnly(Side.CLIENT)
public static Icon bottomIcon;

@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister icon) 
{
	topIcon = icon.registerIcon(Mine_EE.modid.toLowerCase() + ":" + "windTop");
	sideIcon = icon.registerIcon(Mine_EE.modid.toLowerCase() + ":" + "windSide");
	frontIcon = icon.registerIcon(Mine_EE.modid.toLowerCase() + ":" + "windFrontOn");
	bottomIcon = icon.registerIcon(Mine_EE.modid.toLowerCase() + ":" + "windBottom");
}


private void iconz(IconRegister icon, int x,int y,int z) {
	// TODO Auto-generated method stub

}

@Override
public Icon getIcon(int side, int meta) {
	if( side == 1) {
		return topIcon;
	} else if(side != meta) {
		return sideIcon;
	} 
	else if(side == 0)
	{
		return bottomIcon;
	}
	else {
		return frontIcon;
	}
}



private void setDefaultDirection(World world, int x, int y, int z) {
	if(!world.isRemote) {
		int zNeg = world.getBlockId(x, y, z - 1);
		int zPos = world.getBlockId(x, y, z + 1);
		int xNeg = world.getBlockId(x - 1, y, z);
		int xPos = world.getBlockId(x + 1, y, z);
		byte meta = 3;

		if(Block.opaqueCubeLookup[xNeg] && !Block.opaqueCubeLookup[xPos]) meta = 5;
		if(Block.opaqueCubeLookup[xPos] && !Block.opaqueCubeLookup[xNeg]) meta = 4;
		if(Block.opaqueCubeLookup[zNeg] && !Block.opaqueCubeLookup[zPos]) meta = 3;
		if(Block.opaqueCubeLookup[zPos] && !Block.opaqueCubeLookup[zNeg]) meta = 2;

		world.setBlockMetadataWithNotify(x, y, z, meta, 2);
	}
}

@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemstack) {
	int rotation = MathHelper.floor_double((double)(entity.rotationYaw * 4F / 360F) + 0.5D) & 3;

	if(rotation == 0) {
		world.setBlockMetadataWithNotify(x, y, z, 2, 2);
	}

	if(rotation == 1) {
		world.setBlockMetadataWithNotify(x, y, z, 5, 2);
	}

	if(rotation == 2) {
		world.setBlockMetadataWithNotify(x, y, z, 3, 2);
	}

	if(rotation == 3) {
		world.setBlockMetadataWithNotify(x, y, z, 4, 2);
	}
}
}

 

 

 

Its best to only ask questions when you did most of the work yourself.

Posted

Do you have a GitHub? If so, post the link so we have all the code. Else, post the IGuiHandler class and the Container class.

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/

Posted

Do you have a GitHub? If so, post the link so we have all the code. Else, post the IGuiHandler class and the Container class.

 

i do not have github so i will post the container and guihandler

 

container

 

 

 
package Mine_EE_GUI;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;



public class ContainerTurbine extends Container {
private TileEntityTurbine Turbine;
private Turbine blockTurbine;



public ContainerTurbine(InventoryPlayer invPlayer, TileEntityTurbine tile_entity) 
{



	this.Turbine = tile_entity;

	 for(int x = 0; x < 9; x++) {
		 this.addSlotToContainer(new Slot(invPlayer, x, 8 + x * 18, 142));
	  }
	 for(int y = 0; y < 3; y++) {
		  for(int x = 0; x < 9; x++) {
		    this.addSlotToContainer(new Slot(invPlayer, 9 + x + y * 9, 8 + x * 18, 84 + y * 18));
		  }
		}
	 for(int y = 0; y < 1; y++) {
		  for(int x = 0; x < 1; x++) {
			    this.addSlotToContainer(new Slot(tile_entity, x + y * 3,116,30));
		  }
		}
	 for(int y = 0; y < 1; y++) {
		  for(int x = 0; x < 1; x++) {
			    this.addSlotToContainer(new Slot(tile_entity, x + y * 3+1,44,30));
		  }
		}
	// this.addSlotToContainer(new Slot(         ID, X, Y));
	// this.addSlotToContainer(new Slot(entity, 237, 62, 17));

}


@Override
public ItemStack transferStackInSlot(EntityPlayer player, int i) {
  Slot slot = getSlot(i);

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

    if(i >= 36) {
      if(!mergeItemStack(itemstack, 0, 36, false)) {
        return null;
      }
    } else if(!mergeItemStack(itemstack, 36, 36 + Turbine.getSizeInventory(), false)) {
      return null;
    }

    if(itemstack.stackSize == 0) {
      slot.putStack(null);
    } else {
      slot.onSlotChanged();
    }
    slot.onPickupFromSlot(player, itemstack); 
    return result;
  }
  return null;
}

@Override
public boolean canInteractWith(EntityPlayer player) 
{

return Turbine.isUseableByPlayer(player);

}






}

 

 

 

 

handler

 

 

 

package Mine_EE;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import Mine_EE_GUI.ContainerDeployer;
import Mine_EE_GUI.ContainerSolar;
import Mine_EE_GUI.ContainerTurbine;
import Mine_EE_GUI.GuiDeployer;
import Mine_EE_GUI.GuiSolar;
import Mine_EE_GUI.GuiTurbine;
import Mine_EE_GUI.TileEntityDeployer;
import Mine_EE_GUI.TileEntitySolar;
import Mine_EE_GUI.TileEntityTurbine;
import Mine_EE_Items.BookGUI;
import Mine_EE_Items.ContainerBook;
import cpw.mods.fml.common.network.IGuiHandler;

public class GuiHandler2 implements IGuiHandler{

@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	TileEntity tile_entity = world.getBlockTileEntity(x, y, z);
	TileEntity tile_entity1 = world.getBlockTileEntity(x, y, z);
	switch(ID)
	{	
	case 34:if(tile_entity != null && tile_entity instanceof TileEntityDeployer) {
		return new ContainerDeployer(player.inventory, (TileEntityDeployer) tile_entity);
	} else {
	return null;
	}
	}
	switch(ID)
	{	
	case 71: if(tile_entity != null && tile_entity instanceof TileEntitySolar) {
		return new ContainerSolar(player.inventory, (TileEntitySolar) tile_entity);

	} else {
	return null;
	}
	}
	switch(ID)
	{	
	case 54: if(tile_entity != null && tile_entity instanceof TileEntityTurbine) {
		return new ContainerTurbine(player.inventory, (TileEntityTurbine) tile_entity);

	} else {
	return null;
	}
	}

	switch(ID)
	{	
	case 66: return ID == 66 && world.getBlockId(x, y, z) == Mine_EE.CraftMain.blockID ? new ContainerBigCrafting(player.inventory, world, x, y, z) : null;
	}
	switch(ID)
	{	
	default: return null;
	case 69: return new ContainerBook(player);
	}

}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	TileEntity tile_entity = world.getBlockTileEntity(x, y, z);
	TileEntity tile_entity1 = world.getBlockTileEntity(x, y, z);
	switch(ID)
	{	
	case 34: if(tile_entity != null && tile_entity instanceof TileEntityDeployer) {
		return new GuiDeployer(player.inventory, (TileEntityDeployer) tile_entity);

	} else {
	return null;
	}
	}
	switch(ID)
	{	
	case 71: if(tile_entity != null && tile_entity instanceof TileEntitySolar) {
		return new GuiSolar(player.inventory, (TileEntitySolar) tile_entity);

	} else {
	return null;
	}
	}
	switch(ID)
	{	
	case 54: if(tile_entity != null && tile_entity instanceof TileEntityTurbine) {
		return new GuiTurbine(player.inventory, (TileEntityTurbine) tile_entity);

	} else {
	return null;
	}
	}
	switch(ID)
	{		
	case 66: return ID == 66 && world.getBlockId(x, y, z) == Mine_EE.CraftMain.blockID ? new GuiBigCraftingTable(player.inventory, world, x, y, z) : null;
	}
	switch(ID)
	{	
	default: return null;
	case 69: return new BookGUI(player);
	}
	}

}




 

 

 

Its best to only ask questions when you did most of the work yourself.

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.