Jump to content

[STILL NOT SOLVED] Custom furnace speed change when a specific item is in slot 6


Recommended Posts

Posted

I would like to know how to make the smelting speed when there is an item in slot 6. Think of it like in IC2 the Overclocker upgrade.

How would you make such a thing? I made an int that sets the smelting speed of the furnace.

I tried this code:

         if(this.electrolysisItemStacks[6].getItem() == Elementum.upgradeSpeed){
        	 finishTime = 1200 /(this.electrolysisItemStacks[6].stackSize + 1); 
         }
         else
         {
        	 finishTime = 1200;
         }

but it crashed when I placed the block in the world.

Posted

Hi

 

Actually I'm not sure that the smelting time can be shortened in the vanilla furnace.  The code below suggests to me that it's fixed at 10 seconds (200 ticks).

 

I don't know why your code fragment causes Minecraft to crash when you place the block.  How were you intending to use finishTime?

 

-TGG

 

 

TileEntityFurnace::
    public void updateEntity()
    {
        boolean flag = this.furnaceBurnTime > 0;
        boolean flag1 = false;
// snip

            if (this.isBurning() && this.canSmelt())
            {
                ++this.furnaceCookTime;

                if (this.furnaceCookTime == 200)
                {
                    this.furnaceCookTime = 0;
                    this.smeltItem();
                    flag1 = true;
                }
            }

 

 

Posted

I don't want to change it in the vanilla furnace. I made my own custom furnace where the cooking time is set to 1200 ticks. The int finishTime is written in the place where the cooking time is supposed to be.

Posted

When you place the block in the world, slot 6 is empty. So this.electrolysisItemStacks[6].getItem() is NULL.

 

Make a check that there is an actual item in the slot before trying to compare it with anything.

         if(this.electrolysisItemStacks[6].getItem() != null && this.electrolysisItemStacks[6].getItem() == Elementum.upgradeSpeed){
        	 finishTime = 1200 /(this.electrolysisItemStacks[6].stackSize + 1); 
         }
         else
         {
        	 finishTime = 1200;
         }

Posted

Well, you need to check one step earlier: electrolysisItemStacks[6] is null at the start, so:

if(electrolysisItemStacks[6] != null && electrolysisItemStacks[6].itemID == Elementum.upgradeSpeed.itemID){

Author of PneumaticCraft, MineChess, Minesweeper Mod and Sokoban Mod. Visit www.minemaarten.com to take a look at them.

Posted

Thank you for the help, but it's still not working.

At least it isn't crashing now :D

No matter how many Speed upgrades I put in, it's still the same speed.

 

Also is there a way for the item to be a metadata item? If yes, then how would the code look like?

 

Here's my tile entity code:

package elementum;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFurnace;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
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.tileentity.TileEntity;

public class TileEntityElectrolysisMachine extends TileEntity implements ISidedInventory
{
    private static final int[] slots_top = new int[] {0};
    private static final int[] slots_bottom = new int[] {3,4,5};
    private static final int[] slots_back = new int[] {2};
    private static final int[] slots_sides = new int[] {1};
    
    private ItemStack electrolysisItemStacks[];
    public int electrolysisBurnTime;
    public int currentItemBurnTime;
    public int electrolysisCookTime;
    private int finishTime;
    private int speedModifier;
    private String customName;
private String localizedName;
    EntityPlayer entityplayer;
public TileEntityElectrolysisMachine()
{
         electrolysisItemStacks = new ItemStack[7];
         electrolysisBurnTime = 0;
         currentItemBurnTime = 0;
         electrolysisCookTime = 0;
         speedModifier = 0;
         if(electrolysisItemStacks[6] != null && electrolysisItemStacks[6].getItem() == Elementum.upgrade){
        	 finishTime = 1200 /(this.electrolysisItemStacks[6].stackSize + 1);
         }
         else
         {
        	 finishTime = 1200;
         }
}
/**
         * Returns the number of slots in the inventory.
         */
public int getSizeInventory()
{
         return electrolysisItemStacks.length;
}	
/**
 * Returns the stack in slot i
 */
public ItemStack getStackInSlot(int i)
{
         return electrolysisItemStacks[i];
}
public void setInventorySlotConatainers(int i, ItemStack itemstack)
{
         electrolysisItemStacks[i] = itemstack;
         if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
         {
                 itemstack.stackSize = getInventoryStackLimit();
         }
}
/**
         * Reads a tile entity from NBT.
         */
public void readFromNBT(NBTTagCompound nbttagcompound)
{
         super.readFromNBT(nbttagcompound);
         NBTTagList nbttaglist = nbttagcompound.getTagList("Items");
         electrolysisItemStacks = new ItemStack[getSizeInventory()];
         for (int i = 0; i < nbttaglist.tagCount(); i++)
         {
                 NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
                 byte byte0 = nbttagcompound1.getByte("Slot");
                 if (byte0 >= 0 && byte0 < electrolysisItemStacks.length)
                 {
                         electrolysisItemStacks[byte0] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
                 }
         }
         electrolysisBurnTime = nbttagcompound.getShort("BurnTime");
         electrolysisCookTime = nbttagcompound.getShort("CookTime");
         currentItemBurnTime = getItemBurnTime(electrolysisItemStacks[1]);
}
/**
         * Writes a tile entity to NBT.
         */
public void writeToNBT(NBTTagCompound nbttagcompound)
{
         super.writeToNBT(nbttagcompound);
         nbttagcompound.setShort("BurnTime", (short)electrolysisBurnTime);
         nbttagcompound.setShort("CookTime", (short)electrolysisCookTime);
         NBTTagList nbttaglist = new NBTTagList();
         for (int i = 0; i < electrolysisItemStacks.length; i++)
         {
                 if (electrolysisItemStacks[i] != null)
                 {
                         NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                         nbttagcompound1.setByte("Slot", (byte)i);
                         electrolysisItemStacks[i].writeToNBT(nbttagcompound1);
                         nbttaglist.appendTag(nbttagcompound1);
                 }
         }
         nbttagcompound.setTag("Items", nbttaglist);
}
public int getInventoryStackLimit()
{
	return 64;
}
public int getCookProgressScaled(int i)
{
         return (electrolysisCookTime * i) / finishTime;
}
public int getBurnTimeRemainingScaled(int i)
{
         if (currentItemBurnTime == 0)
         {
                 currentItemBurnTime = finishTime;
         }
         return (electrolysisBurnTime * i) / currentItemBurnTime;
}

public boolean isBurning()
{
         return electrolysisBurnTime > 0;
}

/*public void updateEntity()
{
         boolean flag = electrolysisBurnTime > 0;
         boolean flag1 = false;
         if (electrolysisBurnTime > 0)
         {
                 electrolysisBurnTime--;
         }
         if (!worldObj.isRemote)
         {
                 if (electrolysisBurnTime == 0 && canSmelt())
                 {
                         currentItemBurnTime = electrolysisBurnTime = getItemBurnTime(electrolysisItemStacks[2]);
                         if (electrolysisBurnTime > 0)
                         {
                                 flag1 = true;
                                 if (electrolysisItemStacks[2] != null)
                                 {
                                         if (electrolysisItemStacks[2].stackSize == 0)
                                         {
                                                 electrolysisItemStacks[2] = new ItemStack(electrolysisItemStacks[2].getItem().setFull3D());
                                         }
                                         else
                                         {
                                                 electrolysisItemStacks[2].stackSize--;
                                         }
                                         if (electrolysisItemStacks[2].stackSize == 0)
                                         {
                                                 electrolysisItemStacks[2] = null;
                                         }
                                 }
                         }
                 }
                 if (isBurning() && canSmelt())
                 {
                         electrolysisCookTime++;
                         if (electrolysisCookTime == finishTime)
                         {
                                 electrolysisCookTime = 0;
                                 smeltItem();
                                 flag1 = true;
                         }
                 }
                 else
                 {
                         electrolysisCookTime = 0;
                 }
                 if (flag != (electrolysisBurnTime > 0))
                 {
                         flag1 = true;
                 }
         }
         if (flag1)
         {
                 onInventoryChanged();
         }
}*/

public void updateEntity()
    {
        boolean flag = this.electrolysisBurnTime > 0;
        boolean flag1 = false;

        if (this.electrolysisBurnTime > 0)
        {
            this.electrolysisBurnTime--;
        }

        if (!this.worldObj.isRemote)
        {
            if (this.electrolysisBurnTime == 0 && this.canSmelt())
            {
                this.currentItemBurnTime = this.electrolysisBurnTime = getItemBurnTime(this.electrolysisItemStacks[2]);

                if (this.electrolysisBurnTime > 0)
                {
                    flag1 = true;

                    if (this.electrolysisItemStacks[2] != null)
                    {
                        --this.electrolysisItemStacks[2].stackSize;

                        if (this.electrolysisItemStacks[2].stackSize == 0)
                        {
                            this.electrolysisItemStacks[2] = this.electrolysisItemStacks[1].getItem().getContainerItemStack(electrolysisItemStacks[2]);
                        }
                    }
                }
            }

            if (this.isBurning() && this.canSmelt())
            {
                ++this.electrolysisCookTime;

                if (this.electrolysisCookTime == finishTime)
                {
                    this.electrolysisCookTime = 0;
                    this.smeltItem();
                    flag1 = true;
                }
            }
            else
            {
                this.electrolysisCookTime = 0;
            }

            if (flag == this.electrolysisCookTime >= 0)
            {
                flag1 = true;
                BlockElectrolysisMachine.updateMachineBlockState(this.electrolysisCookTime > 0, this.worldObj, this.xCoord, this.yCoord, this.zCoord);
            }
        }

        if (flag1)
        {
            this.onInventoryChanged();
        }
    }

private boolean canSmelt()
{
         if (electrolysisItemStacks[0] == null || electrolysisItemStacks[1] == null)
         {
                 return false;
         }
         ItemStack itemstack = ElectrolysisMachineRecipes.getSmeltingResult(electrolysisItemStacks[0].getItem().itemID, electrolysisItemStacks[1].getItem().itemID);
         if (itemstack == null)
         {
                 return false;
         }
         if (electrolysisItemStacks[3] == null)
         {
                 return true;
         }
         if (electrolysisItemStacks[4] == null)
         {
                 return true;
         }
         if (electrolysisItemStacks[5] == null)
         {
                 return true;
         } 
         if (electrolysisItemStacks[3] != null && electrolysisItemStacks[4] != null && electrolysisItemStacks[5] != null)
         {
                 return false;
         }
         /*if (!electrolysisItemStacks[3].isItemEqual(itemstack))
         {
        	 return false;
         }
         if (electrolysisItemStacks[3].stackSize < getInventoryStackLimit() && electrolysisItemStacks[3].stackSize < electrolysisItemStacks[3].getMaxStackSize())
         {
        	 return true;
         }*/
         else
         {
             //return electrolysisItemStacks[3].stackSize < itemstack.getMaxStackSize();
        	 return false;
         }
}
public void smeltItem()
{
         if (!canSmelt())
         {
                 return;
         }
         ItemStack itemstack = ElectrolysisMachineRecipes.getSmeltingResult(electrolysisItemStacks[0].getItem().itemID, electrolysisItemStacks[1].getItem().itemID);
         if (electrolysisItemStacks[3] == null)
         {
                 electrolysisItemStacks[3] = itemstack.copy();
         }
         else if(electrolysisItemStacks[3] != null)
         {
        	 if (electrolysisItemStacks[4] == null)
             {
        		 electrolysisItemStacks[4] = itemstack.copy();
             }
        	 else if (electrolysisItemStacks[4] != null)
        	 {
            	 if (electrolysisItemStacks[5] == null)
                 {
            		 electrolysisItemStacks[5] = itemstack.copy();
                 }
        	 }
         }
         /*else if (electrolysisItemStacks[3].itemID == itemstack.itemID)
         {
                 electrolysisItemStacks[3].stackSize++;
         }*/
         for (int i = 0; i < 2; i++)
         {
                 if (electrolysisItemStacks[i].stackSize <= 0)
                 {
                         electrolysisItemStacks[i] = new ItemStack(electrolysisItemStacks[i].getItem().setFull3D());
                 }
                 else
                 {
                         electrolysisItemStacks[i].stackSize--;
                 }
                 if (electrolysisItemStacks[i].stackSize <= 0)
                 {
                         electrolysisItemStacks[i] = null;
                 }
         }
}
private static int getItemBurnTime(ItemStack itemstack)
{
         if (itemstack == null)
         {
                 return 0;
         }
         int i = itemstack.getItem().itemID;
         Item item = itemstack.getItem();

         if (itemstack.getItem() instanceof ItemBlock && Block.blocksList[i] != null)
         {
             Block block = Block.blocksList[i];

             if (block == Block.woodSingleSlab)
             {
                 return 150;
             }

             if (block.blockMaterial == Material.wood)
             {
                 return 300;
             }

             if (block == Block.coalBlock)
             {
                 return 16000;
             }
         }

         if (item instanceof ItemTool && ((ItemTool) item).getToolMaterialName().equals("WOOD")) return 200;
         if (item instanceof ItemSword && ((ItemSword) item).getToolMaterialName().equals("WOOD")) return 200;
         if (item instanceof ItemHoe && ((ItemHoe) item).getMaterialName().equals("WOOD")) return 200;
         if (i == Item.stick.itemID) return 100;
         if (i == Item.coal.itemID) return 1600;
         if (i == Item.bucketLava.itemID) return 20000;
         if (i == Block.sapling.blockID) return 100;
         if (i == Item.blazeRod.itemID) return 2400;
         return GameRegistry.getFuelValue(itemstack);
}

public static boolean isItemFuel(ItemStack itemstack)
{
    return getItemBurnTime(itemstack) > 0;
}
/**
         * Do not make give this method the name canInteractWith because it clashes with Container
         */
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
         if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this)
         {
                 return false;
         }
         else
         {
                 return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
         }
}
/**
         * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new
         * stack.
         */
public ItemStack decrStackSize(int i, int j)
{
         if (electrolysisItemStacks[i] != null)
         {
                 if (electrolysisItemStacks[i].stackSize <= j)
                 {
                         ItemStack itemstack = electrolysisItemStacks[i];
                         electrolysisItemStacks[i] = null;
                         return itemstack;
                 }
                 ItemStack itemstack1 = electrolysisItemStacks[i].splitStack(j);
                 if (electrolysisItemStacks[i].stackSize == 0)
                 {
                         electrolysisItemStacks[i] = null;
                 }
                 return itemstack1;
         }
         else
         {
                 return null;
         }
}
/**
         * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
         */
public void setInventorySlotContents(int i, ItemStack itemstack)
{
         electrolysisItemStacks[i] = itemstack;
         if (itemstack != null && itemstack.stackSize > getInventoryStackLimit())
         {
                 itemstack.stackSize = getInventoryStackLimit();
         }
}
/**
         * Returns the name of the inventory.
         */
public String getInvName()
{
         return "container.electrolysisMachine";
}
public void openChest()
{
}
public void closeChest()
{
}
/**
         * When some containers are closed they call this on each slot, then drop whatever it returns as an EntityItem -
         * like when you close a workbench GUI.
         */
public ItemStack getStackInSlotOnClosing(int i)
{
         if (electrolysisItemStacks[i] != null)
         {
                 ItemStack itemstack = electrolysisItemStacks[i];
                 electrolysisItemStacks[i] = null;
                 return itemstack;
         }
         else
         {
                 return null;
         }
}
@Override
public boolean isInvNameLocalized()
{
         return (this.customName != null) && (this.customName.length() > 0);
}
public void setCustomName(String name)
{
         this.customName = name;
}
    public boolean isItemValidForSlot(int par1, ItemStack par2ItemStack)
    {
        return par1 == 3 ? false : (par1 == 2 ? isItemFuel(par2ItemStack) : true);
    }
    
public void setGuiDisplayName(String displayName) {
this.localizedName = displayName;
}

public int[] getAccessibleSlotsFromSide(int side)
{
	return side == 0 ? slots_bottom : (side == 1 ? slots_top : side == 5 ? slots_back : slots_sides);
}

public boolean canInsertItem(int slot, ItemStack item, int side)
{
	return this.isItemValidForSlot(slot, item);
}

public boolean canExtractItem(int slot, ItemStack item, int side)
{
	return side != 0 || slot != 1 || item.itemID == Item.bucketEmpty.itemID;
}
}

Posted

I am using it in:

public int getCookProgressScaled(int i)
{
         return (electrolysisCookTime * i) / finishTime;
}
public int getBurnTimeRemainingScaled(int i)
{
         if (currentItemBurnTime == 0)
         {
                 currentItemBurnTime = finishTime;
         }
         return (electrolysisBurnTime * i) / currentItemBurnTime;
}

and

if (this.isBurning() && this.canSmelt())
            {
                ++this.electrolysisCookTime;

                if (this.electrolysisCookTime == finishTime)
                {
                    this.electrolysisCookTime = 0;
                    this.smeltItem();
                    flag1 = true;
                }
            }

 

Basically it's in the place where the number of ticks, which are required to smelt items, is supposed to be.

Posted

Hi

 

I've had a look through the code and I have to admit I don't really understand what you're trying to do.

 

In particular this bit

         if(electrolysisItemStacks[6] != null && electrolysisItemStacks[6].getItem() == Elementum.upgrade){
        	 finishTime = 1200 /(this.electrolysisItemStacks[6].stackSize + 1);
         }

won't electrolysisItemStacks[6] always be null, since you only just created it?

 

Perhaps you could write a paragraph describing to us in more detail how your furnace should work, eg

(1) The furnace will have an extra seven slots

(2) Each slot can hold an Elementum

(3) The more slots are filled with Elementum, the faster the smelting time according to the formula xxx

(etc)

 

But anyway, to help you track down why your code isn't working the way you expect, I'd suggest you add logging code at key points, eg:

 

if (this.isBurning() && this.canSmelt())
            {
                ++this.electrolysisCookTime;
System.out.println("Current electrolysisCookTime:" + this.electrolysisCookTime + " -> " + finishTime);

                if (this.electrolysisCookTime == finishTime)
                {
                    this.electrolysisCookTime = 0;
                    this.smeltItem();
                    flag1 = true;
                }
            }

 

and

 

	public TileEntityElectrolysisMachine()
{
         electrolysisItemStacks = new ItemStack[7];
         electrolysisBurnTime = 0;
         currentItemBurnTime = 0;
         electrolysisCookTime = 0;
         speedModifier = 0;
         if(electrolysisItemStacks[6] != null && electrolysisItemStacks[6].getItem() == Elementum.upgrade){
        	 finishTime = 1200 /(this.electrolysisItemStacks[6].stackSize + 1);
         }
         else
         {
        	 finishTime = 1200;
         }
System.out.println("finishTime = " + finishTime);
}

 

-TGG

Posted

I wrote this for you - you can feel special :)

//TileEntity
public int Power; //Time needed to smelt an item
public TileEntity()
{
//Other stuff
Power = 200; //Well you need to declare first Power (I mean - maybe not, never checked)
}
//Since you need to check for stack in your [6] slot everytime they change I would suggest using updateEntity
public void updateEntity()
{
//You need to call this right at the beggining!
if(this.ItemStacks[6] != null) //Checks if Slot[6] is not null
{
	if(this.ItemStacks[6].itemID == MyMod.booster.itemID) //Checks if there is booster inside - and yes - use freaking ID's, not getItem() -.-
	{
		int x = this.ItemStacks[6].stackSize; //Well, you wanted that: more boosters = faster smelting?
		this.Power = 200 - 2*x; //10sec - 1/5sec for every booster in slot [6]
//It is VERY important to make sure that maxStackSize of booster will not make your Power go less than 1.
//Here: with 64xbooster you will get 200-128-1=71 ticks to smelt item (-1 is from array index, or whatever you call it)
	}
}
else
{
	this.Power = 200; //10sec
}
}

This works perfectly! And I mean it - just checked in eclipse!

Also: I did int x inside updateEntity - don't do that, make it global :)

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

Posted

Thank you very much!

It works fine, except one thing.

It speeds it up perfectly, but it doesn't update the GUI when I put the upgrades in or out of the slot. You have to reopen the tile entity for the GUI to update.

Isn't there any quick fix?

Posted

Jeerdus, I'd just drop in the simplest and best advice I can give:

Check out VSWE's excellent course about GUI's. It involves syncing Server<->Client and later covers advance syncing which does not req. you to reopen your gui :) 

If you guys dont get it.. then well ya.. try harder...

Posted

Thanks, watched the tutorial and started to understand this thing! :D

Thank you very much for your help!

 

The tutorials are in multiple parts, and he has some for other topics.

I'm glad you liked them and I highly recommend that you watch all the videos in the series, it will make you able to create rather impressive and advance GUI's ;)

If you guys dont get it.. then well ya.. try harder...

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

    • 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() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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