Jump to content

Recommended Posts

Posted

I've been looking for an answer to my question for a while. How exactly would I get an item to change (I know it "deletes" itself then spawns another where it was) when it is in water. I've read around and looked around at different things in the EntityItem code and noticed there is a inWater() method. Can I use that? Then how would I "change" the item.

 

I would be taking a blaze rod and "changing" it into a cooled blaze rod which is an item in my mod.

Posted

For vanilla items (Blaze Rod) you need to use EntityJoinedWorld event and if entity is EntityItem check if it is Blaze Rod. If so - cancel spawning (kill it) and spawn other entity. That other entity will be an extension to EntityItem with changes applied. You want to override onUpdate() method and check if item is wet or is in water (wet also check rain I think, there were some differences, you would just have to read some vanilla code). If so - again - kill item and spawn new one (normal EntityItem with your Cooled Blaze Rode).

 

This covers logical side. If you have questions about coding it - look into vanilla for spawning codes or ask here.

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

Posted

I'd do what Ernio instructed firsthand

 

Here's an example of how I'd handle the updating

//gather position data
World world = entity.worldObj;
double x = entity.posX;
double y = entity.posY;
double z = entity.posZ;

//checks if position is in water
if(world.getBlock(x, y, z).getMaterial() == Material.water){

//destroy current entity
this.setdead

//setting up new cool rod entity constructor and placement
EntityItem rod= new EntityItem(world, x, y, z, new ItemStack(moditem.cooled_rod, 1, 0))
rod.setLocationAndAngles(x,y,z, 0.0F, 0.0F);

//spawns the newly constructed entity
world.spawnEntityInWorld(rod);
}

 

Posted

 

 

long ago i try a diferent aproach

in mi mod i make steel bi heating and iron ingot in the furnace and later to cold down convined it whit a water bucket in the workbench

 

mi original idea wass to toos the hot iron item into water a shhhhh sound and the item becomes an aceromercenario Ingot

 

i think you are triying to make the same

 

 

i  make and event to wach whenever the player throws something

if this someting is hotIron create a invisible entity to wach over it for 20 ticks then die,

if the Item is inside a water block whith 20 tics kill it and drop mi aceroMercenario ingot

 

mi fail was i could get the item from the entityItem so i could not know what the player has droped, i redoo the code some minutes ago still have the trouble

	if (event.entity instanceof EntityItem) {

		EntityItem itm = (EntityItem) event.entity;

		System.out.println("# Someone drops something");

		ItemStack stack = itm.getEntityItem();

		if (stack != null)
		{
			System.out.println("# is a "+stack.getUnlocalizedName());

		}

	}

 

 

this is always returning

System.out.println("# is a"+stack.getUnlocalizedName());

 

is allways returning

 

[13:26:06] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityConstructing:76]: # Someone drops something
[13:26:06] [server thread/ERROR]: Item entity 244798 has no item?!
[13:26:06] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityConstructing:85]: # is a tile.stone.stone

 

has no item?!  and # is atile.stone.stone  wtf allways say the same no mather what i drop 

 

 

i just get tired and leave this this way and made code on mi hotIron item class to make steel when rigthClick a filled Cauldrom

 

 

 

Posted
Item entity 244798 has no item?!

 

Did you use Eclipse to see the vanilla code that prints this message? I suspect that you're looking at the stack either too soon or too late to get a valid return value. You might need to use a different event. To which did you subscribe? Show more code for context.

 

tile.stone.stone

 

You already got a zero in your stack, and stone follows from zero (that's its ID). When you fix the first problem, this one should clear up.

 

However, your cauldron workaround is nice -- it creates a use for cauldrons.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

u oooo

 

well long ago idont remenber exactly what i wass using but now im using

 

MinecraftForge.EVENT_BUS.register(new mercenarymod.items.armasdefuego.tickHandlerArmas()); // Main event Handler

 

and the event is

 

//########################################################################################################################3
@SubscribeEvent
public void onEntityConstructing(EntityConstructing event) {
	// Register extended entity properties
	// Herd animals


	if (event.entity instanceof EntityItem) {


		System.out.println("# Someone drops something");

		EntityItem itm = (EntityItem) event.entity;

		ItemStack stack = itm.getEntityItem();

		if (stack != null)
		{
			System.out.println("# is a"+stack.getUnlocalizedName());

		}
	}


	/*
	if (event.entity instanceof fantasmaMercenario) {
		// DEBUG
		// System.out.println(("OnEntityConstructing register
		// FantasmaMercenario extended properties");

		event.entity.registerExtendedProperties("ExtendedPropertiesFantasmaMercenario", new ExtendedPropertiesFantasmaMercenario());
	}
	 */

	if (event.entity instanceof EntityLivingBase) {
		// DEBUG
		// System.out.println(("OnEntityConstructing register EntityLiving
		// extended properties");

		event.entity.registerExtendedProperties("ExtendedPropertiesMercenary", new ExtendedPropertiesMercenary() );
	}

}

//########################################################################################################################3

 

i alredy read that inth entityItem class

 

/**

    * Returns the ItemStack corresponding to the Entity (Note: if no item exists, will log an error but still return an

    * ItemStack containing Block.stone)

    */

    public ItemStack getEntityItem()

 

 

 

but why this entity has no item por example if i throw and apple from mi inventory, is an apple has the apple texture if i pickup back  still and apple

 

or this values needs some ticks before load ?

 

 

 

 

 

 

Posted

First things first: Toss event is NOT the right tool in this case. It will never cover all cases of item-dropping and suggested approach of making watcher entity is unnecessary performance hit (good outside box thinking when you didn't know Forge yet).

 

As to why EntityItem would ever give you bad data:

 

EntityConstructing, you wrote:

@SubscribeEvent
public void onEntityConstructing(EntityConstructing event) {
	if (event.entity instanceof EntityItem) {
		EntityItem itm = (EntityItem) event.entity;
		ItemStack stack = itm.getEntityItem(); // BAAAAD

 

EntityConstructing is called at end of Entity.class constructor. Logically - anything written in EntityItem constructor will not yet be accessible to this event. That includes "event.entity.getEntityItem()".

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

Posted

uuu well sounds legit

 

soo when the event onEntityConstructing(EntityConstructing event)  trigers the EntityItem has not alredy been droped in the world and dont'n has yet the itemStack value defined  thus always is a stone tile when i try to read it

 

jummmm

thas not good i can thing in something diferent to create an invisible entity to wacht over the dropped item

wait a few ticks  check if its hotIron  check if its in water  the kill it an create an aceroMercenario Item

 

this entity solution dont's like me,  much over having in count that i have create some tools that break masively blocks droping their contens

so this cause to duply the amount of entityes in a place, and alredy only the droped blocks causes lag 

 

 

Posted

This covers logical side. If you have questions about coding it - look into vanilla for spawning codes or ask here.

 

Thanks. That actually really helps. I'll try it out tonight when I have a chance. I'll probably look into some of the code (I believe I would be looking in the EntityItem class correct?)  and if I have any clarification questions I'll ask them. I'm pretty new to MinecraftForge so this helps a lot. :)

 

EDIT:

To kill an entity I assume I would use this.isDead(true), correct?

Posted

ohh

ya coji la idea

 

i just remember reading something about a custome EntityItem whith this i could just catch the EntityItem if is hotIron, store the values from the position the moving direction and the quantity of items in the stack then create a custom EntityItem just copy paste extend from original but whith code to check if in water  kill the original and set the values to the custom and is done whiout trouble of overpopulating the chunk

 

//########################################################################################################################3
// replace toss item
@SubscribeEvent
public void onPlayerToss(ItemTossEvent event) {


if (event.entity instanceof EntityItem) {


		System.out.println("# Someone drops something");

		EntityItem itm = (EntityItem) event.entity;

		ItemStack stack = itm.getEntityItem();

		if (stack != null)
		{
			System.out.println("#1 is a"+stack.getUnlocalizedName());

			if (stack.getItem() == MercenaryModItems.hierroAlrojo )// if stack is equal to my hot iron item 
			{
				int amount = stack.stackSize;

				//create a custom EntityItem that checks if its in watter

			}
		}
	}

}	

 

 

 

 

 

[16:39:53] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:39:53] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is afusilM4A1
[16:40:02] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:02] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is afusilM4A1
[16:40:04] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:04] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aradioMercenaria
[16:40:06] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:06] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aitem.modmercenario_cuchillomercenario
[16:40:08] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:08] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aitem.monsterPlacer
[16:40:09] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:09] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aitem.monsterPlacer
[16:40:10] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:10] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aitem.monsterPlacer
[16:40:13] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:183]: # Someone drops something
[16:40:13] [server thread/INFO] [sTDOUT]: [mercenarymod.items.armasdefuego.tickHandlerArmas:onEntityReplace:191]: #1 is aitem.monsterPlacer

Posted

Here's an update as to what I have so far:

 

I've made a custom EntityItem class called ToolExpEntityItem, I just copy pasted the original EntityItem and changed some names around. I've @Override the onUpdate() method. I've been looking at perromercenary00's code and what they've been doing. I've looked in the original code but can't find onPlayerToss(ItemTossEvent event) so I'm assuming its a new method you've made.

 

Despite all of this, I'm kind of stumped as to what to do now. I know I have to do something along the lines of:

//Probably in onUpdate() but could be elsewhere

ItemStack stack= this.getItemStack();
if(stack != null){
        if(stack.inWater){
                //grab the thrown entity (blazerod)
               this.setDead;
               //spawn my own cooled blazerod
        }
}

 

Any help is greatly appreciated!  ;D

Posted
I've looked in the original code but can't find onPlayerToss(ItemTossEvent event) so I'm assuming its a new method you've made.

 

Its an event not a method, and completely useless to you.  Both as previously stated and because when it does fire, it fires when the item is immediately removed from the player's inventory.  That is, 3 blocks away from the water.

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.

Posted

I've made a custom EntityItem class called ToolExpEntityItem, I just copy pasted the original EntityItem...

Copy pasted? Why not extend? And, having created this class, when will the world ever spawn one so it can do something for you?

 

I think you want to extend EntityItem so the objects of your custom class will still count as EntityItem in vanilla code that might operate on them. Otherwise some things may break.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

It may be easier to just create your own "cauldron" filled with water that can check for whatever entities you throw into it with AABB rather than trying to watch events for vanilla items

 

I'm pretty new to Forge so would you be able to explain this AABB to me? I've seen it mentioned before but am unsure where to even find it in the vanilla code

 

As to creating my own cauldron, I've made a new class for the cauldron, extending the vanilla cauldron and overriding some methods. I've added the following code to handle the creation of my cooled blaze rod

//This is an excerpt from the onBlockActivated() event
int i = ((Integer)state.getValue(LEVEL)).intValue();
                Item item = itemstack.getItem();
                
                //Turns Blaze Rod into Cooled Blaze Rod
                if(item == Items.blaze_rod){
                	if( i < 3){
                		if(!playerIn.capabilities.isCreativeMode){
                			playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, new ItemStack(ToolExpansionItems.cooled_blaze_rod));
                		}
                		this.setWaterLevel(worldIn, pos, state, i - 1);
                	}
                	return true;
                }

 

Am I right in doing this? This is honestly out of where I usually am and all of this is pretty new to me.

 

Thanks for all the help given so far, it is greatly appreciated! :D

 

EDIT:

 

Just realilzed the above handles rightclicking the cauldron, and not throwing the item into it. So close..

 

/EDIT

 

I've made a custom EntityItem class called ToolExpEntityItem, I just copy pasted the original EntityItem...

I think you want to extend EntityItem so the objects of your custom class will still count as EntityItem in vanilla code that might operate on them. Otherwise some things may break.

 

So just create a class and extend it. Should there be anything specific in it that I would need for this not to break?

 

Posted

For vanilla items (Blaze Rod) you need to use EntityJoinedWorld event and if entity is EntityItem check if it is Blaze Rod...

 

Coming back to this, where would I use this EntityJoinedWorld event exactly?

Posted

In an event handler.

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.

Posted

In an event handler.

 

I'll look over some documentation and tutorials and stuff for event handlers. Thanks! (I kinda feel like it was really obvious that events would be needed.. Oh well :3 )

 

(Thinking out loud here)

 

Since I'm checking if the player throws a blaze rod into a water source, I could use onPlayerToss event. However, you (Draco18s) said that its fired when the item is actually tossed.

 

because when it does fire, it fires when the item is immediately removed from the player's inventory.  That is, 3 blocks away from the water.

 

So instead, as Ernio said, I could use a EntityJoinedEvent. Okay I think I'm getting the hang of this. Code would probably go like this correct?:

 


public void onEvent(EntityJoinedWorldEvent event)
{
        //check if entity is blaze rod
        //if it is, check if in water
        //capture coordinates
        //setDead
        //spawn cooled blaze rod at the captured coordinates 
}

 

 

Posted

I am going to crucify you here a little bit, so sorry my friend. :D

 

CAN YOU READ GODDAMIT?! (There is a NEED for heavier words here)

 

For vanilla items (Blaze Rod) you need to use EntityJoinedWorld event and if entity is EntityItem check if it is Blaze Rod. If so - cancel spawning (kill it) and spawn other entity. That other entity will be an extension to EntityItem with changes applied. You want to override onUpdate() method and check if item is wet or is in water (wet also check rain I think, there were some differences, you would just have to read some vanilla code). If so - again - kill item and spawn new one (normal EntityItem with your Cooled Blaze Rode).

 

You have almost step by step solution for problem at start of thread (quote above) and you still wonder what to do. :o And seriously people - you keep on throwing random ideas that are simply wrong in this case, and that only leads to confusing our friend (OP) here. I am speaking on behalf of proper way of solving this - how do expect e.g TossEvent to solve his problem?

 

public void onEvent(EntityJoinedWorldEvent event)
{
        //check if entity is blaze rod
        //if it is, check if in water
        //capture coordinates
        //setDead
        //spawn cooled blaze rod at the captured coordinates 
}

 

Rather:

public void onEvent(EntityJoinedWorldEvent event)
{
        //check if entity is EntityItem
        //check if EntityItem contains Blaze Rod
        //if it is Blaze Rod -> cancel spawning and spawn OTHER SpecialEntityItem
        //SpecialEntityItem is a extension of EntityItem with onUpdate() method overrided.
        //onUpdate() method has additional check for water.
}

class SpecialEntityItem extends EntityItem
{
//constructors and shit
@Override
public void onUpdate()
{
       //Check for water/wetness
       //If true -> kill this entity and spawn new one. New one is EntityItem with Cooled Rod inside.
}

 

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

Posted

 

You have almost step by step solution for problem at start of thread (quote above) and you still wonder what to do.

I am quite aware of your post at the start of the thread. I keep asking questions because honestly this is my first time spawning items and using event listeners/handlers and I've only been modding for about a month (everything before this has been pretty basic. Create Item/Block. Model it. Apply textures. All the basic stuff).

:o And seriously people - you keep on throwing random ideas that are simply wrong in this case, and that only leads to confusing our friend (OP) here...

Thank you. Finally someone points out I am pretty confused on what to do for this. This is why I came here; to get unconfused. Pretty much everything here that has been suggested to do I've encountered for the first time, simply because this is my first time doing this kind of stuff. And yes, I do know Java ;P

Rather:

public void onEvent(EntityJoinedWorldEvent event)
{
        //check if entity is EntityItem
        //check if EntityItem contains Blaze Rod
        //if it is Blaze Rod -> cancel spawning and spawn OTHER SpecialEntityItem
        //SpecialEntityItem is a extension of EntityItem with onUpdate() method overrided.
        //onUpdate() method has additional check for water.
}

class SpecialEntityItem extends EntityItem
{
//constructors and shit
@Override
public void onUpdate()
{
       //Check for water/wetness
       //If true -> kill this entity and spawn new one. New one is EntityItem with Cooled Rod inside.
}

 

 

Alright I get this, let me clear some stuff up for myself so it doesn't cause problems later down the road.

 

How would I go about doing this? My idea is:

if(entity instanceof EntityItem){
       if(EntityItem == Items.blaze_rod){
              entity.setDead;
              //spawn specialEntityItem
       }
}

 

But for some reason that looks wrong..

 

Also, when you say:

//SpecialEntityItem is a extension of EntityItem ..

Will that SpecialEntityItem be my CooledBlazeRod class or a different class?

 

Honestly, thanks for your help. I've actually learned quite a lot as to how to do stuff, but am still trying to grasp the concepts

 

EDIT:

Which class EXACTLY should I be putting the onEvent(EntityJoinWorldEvent event)? Should it be in its own class or somewhere else? eg, in CooledBlazeRod or something.

Posted

Prerequisites:

- Learn what is Forge Event, how to make a class with Event methods and how to register it (on game startup).

- Try it, print something in event, make it actually work.

- Understand concept of Item, Block, TileEntity and especially Entity - those are one of pillars of minecraft.

 

DO NOT continue without Events knowledge (GOOGLE).

 

Now:

public class ForgeEvents
{
@SubscribeEvent
public void onEntityJoined(EntityJoinWorldEvent event)
{
	if (event.entity instanceof EntityItem)
	{
		if (((EntityItem) event.entity).getEntityItem().getItem() == Items.blaze_rod)
		{
			event.setCanceled(true);
			WaterEntityItem wEntity = new WaterEntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY, event.entity.posZ, ((EntityItem) event.entity).getEntityItem());
			event.entity.worldObj.spawnEntityInWorld(wEntity);
		}
	}
}
}

public class WaterEntityItem extends EntityItem
{
//constructors

@Override
public void onUpdate()
{
if (isInWater())
{
	this.setDead();
	EntityItem entity = new EntityItem(this.worldObj, this.posX, this.posY, this.posZ, new ItemStack(MyItems.cooled_blaze_rod));
	this.worldObj.spawnEntityInWorld(entity);
}
}

 

Code written from memory so some parts will not work. Fixing it I am leaving as an exerice.

 

YOU FOOL! I TOLD YOU TO NOT READ IT BEFORE FULFILLING PREREQUISITES! :D

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

Posted

Can your WaterEntityItem just be my CooledBlazeRod class or does that not work?

 

EDIT:

 

Going to try it with it. Honestly, it probably should work. Unless I'm missing something...

 

EDIT:

 

Instead I made a new class called SpecialEntityItem, which actually spawns the CooledBlazeRod, and is called by the EntityJoinWorldEvent handler, which just @SubscribeEvent the event. Testing now to see if it all works

Posted

Was just going to add an edit to my last post but the post quickly became fairly lengthy.

 

So... I'm having problems when my event is fired. It completely crashes the game, giving me this error (put it in Pastebin to save room on this post) http://pastebin.com/EA2vQCxS (and by crash I mean the game still runs but nothing can happen)

 

I honestly have no idea what is going wrong. But I'll post the code on Pastebin as well so you guys can maybe find what is going on.

SpecialEntityItem:

http://pastebin.com/fLNXCvBs

EntityJoinWorldEventHandler:

http://pastebin.com/ES9A2igD

(this one is just how I register the events so will just be a code block):

public void registerEventListeners(){
    	//DEBUG
    	System.out.println("Registering Events");
    	//Register Events
    	MinecraftForge.EVENT_BUS.register(new EntityJoinWorldEventHandler());
    	MinecraftForge.EVENT_BUS.register(new FillBucketEventHandler());
    	//MinecraftForge.EVENT_BUS.register(new PlayerDropsEventHandler());
    }

(It is called from the following method):

@EventHandler
    public void init(FMLInitializationEvent event)
    {
	proxy.registerRenders();
	Recipes.addRecipes();
	SmeltingRecipes.addRecipes();
	registerEventListeners();
    }

 

Honestly I'm not sure what's going on :-\

Posted
Can your WaterEntityItem just be my CooledBlazeRod class

 

I think he was using a descriptive name where you would put your name for the entityItem to spawn in water. However, that is not quite the item (cooledBlazeRod). An entityItem is a subclass of Entity, not Item. You don't actually get to the itemStack of your Item until picking up the Entity. Clear as mud right?

 

BTW, Another source of confusion is that MC and Forge often offer multiple ways to solve various similar problems, with some techniques enabling a mod to do more (but usually paying a penalty in more coding or something). Depending on how readers interpreted what you're trying to do, they may have offered up solutions to the wrong problem.

 

Me, I would have started by trying to detect wetness of the entityItem rather than trying to intercept the initial spawning in the world (because the entityItem can move, fall, or have blocks change around it). However, I probably would have run into problems and ended up doing what your onto now. I have to say that immediately substituting one's own entityItem at spawning gives you many more ways to control it. In fact, you might not even need to replace it when it cools. It might just need to change color and remember that it has cooled so that it returns the right kind of itemStack when it is picked up. Also see combineItems in EntityItem to make sure that dissimilar rods do not combine.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

That error looks like an endless loop. Your event handler is calling something that invokes the same handler etc etc etc...

 

You need to code it so there's always a way out, even if one spawn leads to another.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

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.