Jump to content

Recommended Posts

Posted

if (event.entity instanceof EntityItem && !(event.entity instanceof SpecialEntityItem))

 

Trying it out, doesn't crash :3 also, whenever the event (EntityJoinWorldEvent) is triggered, I'm getting the same problem as perromercenary00 did, where it says "Item entity x has no item?!", where x is a number. As well, whenever I drop the blaze rod, I instantly pick it up. Not really sure what to do about that but everything else seems to work fine

Posted

NBTTagCompound nbt = new NBTTagCompound();
oldEntity.writeToNBTOptional(nbt);
newEntity.readFromNBT(nbt);

 

This will copy any settings over from the old to the new entity.

 

What would I need to do for this to work and where would I put it?

Posted

That "no item" error message happens when the entityItem has no itemStack associated with it. It is probably solved by d7's suggestion, but in general, I think a call to setEntityItemStack is in order for all entityItems (something that happens in the NBT methods). It's this setting of the itemStack that one entityItem might be able to handle the entire life cycle of your entity from blaze rod to cooling to pick up without being replaced again.

 

PS: Operate on the old and new entities inside your event handler where you have both at hand.

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

Changed my EntityJoinWorldEvent method in my EntityJoinWorldEventHandler to this, like d7 suggested to do (adding NBTTagCompound):

if(((EntityItem)event.entity).getEntityItem().getItem() == Items.blaze_rod)
		{
			event.setCanceled(true);
			SpecialEntityItem entityItem = new SpecialEntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY, event.entity.posZ, ((EntityItem)event.entity).getEntityItem());
			NBTTagCompound nbt = new NBTTagCompound();
			event.entity.writeToNBTOptional(nbt);
			entityItem.readFromNBT(nbt);
			event.entity.worldObj.spawnEntityInWorld(entityItem);
		}

 

The Blaze Rod now drops like a regular blaze rod, however, I cannot pick it back up, and just "bounces" in the same spot(looks like it is dropping after a 2 second delay where I dropped it). It also, in contact with water, does not do anything. Any suggestions as to why this is?

Posted

You're down to the level of the debugger. Set breaks and see what's really happening.

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

:D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D :D

 

Omg it finally works! I set some debug System.out.println() to see if it it reaches where I want it to, but everything worked out fine. Then I thought, EntityItem has a way more extensive onUpdate() method/event than my SpecialEntityItem did. So I copy pasted (probably not the best thing to do but it gets the result I want) the rest of it. I noticed this little piece of code that is in the vanilla EntityItem onUpdate():

if (!this.worldObj.isRemote)
                {
                    this.searchForOtherItemsNearby();
                }

 

However it is a private method that if you implement into the class, you need more methods which lead to a dead end (at least for me). So, I commented it out and Voila! it works. It drops the Blaze Rod, it acts as a vanilla Blaze Rod, and when it hits water, it "changes" into my cooledBlazeRod. It does everything I want it to do at the moment.

 

onUpdate() in SpecialEntityItem

 

 

Code:

@Override
public void onUpdate()
{
	if(this.inWater)
	{
		this.setDead();
		//DEBUG
		System.out.println("this set to Dead");
		EntityItem entity = new EntityItem(worldObj, this.posX, this.posY, this.posZ);
		//DEBUG
		System.out.println("EntityItem entity created at this position");
		entity.setEntityItemStack(new ItemStack(ToolExpansionItems.cooledFireRod));
		//DEBUG
		System.out.println("entity's EntityItemStack set to cooledFireRod");
		worldObj.spawnEntityInWorld(entity);
		//DEBUG
		System.out.println("entity spawned in world");	
	}

	ItemStack stack = this.getDataWatcher().getWatchableObjectItemStack(10);
	if (stack != null && stack.getItem() != null && stack.getItem().onEntityItemUpdate(this)) return;
        if (this.getEntityItem() == null)
        {
            this.setDead();
        }
        else
        {
            super.onUpdate();

            if (this.delayBeforeCanPickup > 0 && this.delayBeforeCanPickup != 32767)
            {
                --this.delayBeforeCanPickup;
            }

            this.prevPosX = this.posX;
            this.prevPosY = this.posY;
            this.prevPosZ = this.posZ;
            this.motionY -= 0.03999999910593033D;
            this.noClip = this.pushOutOfBlocks(this.posX, (this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D, this.posZ);
            this.moveEntity(this.motionX, this.motionY, this.motionZ);
            boolean flag = (int)this.prevPosX != (int)this.posX || (int)this.prevPosY != (int)this.posY || (int)this.prevPosZ != (int)this.posZ;

            if (flag || this.ticksExisted % 25 == 0)
            {
                if (this.worldObj.getBlockState(new BlockPos(this)).getBlock().getMaterial() == Material.lava)
                {
                    this.motionY = 0.20000000298023224D;
                    this.motionX = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
                    this.motionZ = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
                    this.playSound("random.fizz", 0.4F, 2.0F + this.rand.nextFloat() * 0.4F);
                }
                /*
                if (!this.worldObj.isRemote)
                {
                    this.searchForOtherItemsNearby();
                }*/
            }

            float f = 0.98F;

            if (this.onGround)
            {
                f = this.worldObj.getBlockState(new BlockPos(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.posZ))).getBlock().slipperiness * 0.98F;
            }

            this.motionX *= (double)f;
            this.motionY *= 0.9800000190734863D;
            this.motionZ *= (double)f;

            if (this.onGround)
            {
                this.motionY *= -0.5D;
            }

            if (this.age != -32768)
            {
                ++this.age;
            }

            this.handleWaterMovement();

            ItemStack item = getDataWatcher().getWatchableObjectItemStack(10);

            if (!this.worldObj.isRemote && this.age >= lifespan)
            {
                int hook = net.minecraftforge.event.ForgeEventFactory.onItemExpire(this, item);
                if (hook < 0) this.setDead();
                else          this.lifespan += hook;
            }
            if (item != null && item.stackSize <= 0)
            {
                this.setDead();
            }
        }
}

 

 

 

onEvent(EntityJoinWorldEvent event) in my EntityJoinWorldEventHandler class

 

 

Code:

@SubscribeEvent(priority=EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
	if(event.entity instanceof EntityItem && !(event.entity instanceof SpecialEntityItem))
	{
		if(((EntityItem)event.entity).getEntityItem().getItem() == Items.blaze_rod)
		{
			event.setCanceled(true);
			//DEBUG
			System.out.println("EntityJoinWorldEvent has been canceled");
			SpecialEntityItem entityItem = new SpecialEntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY, event.entity.posZ);
			//DEBUG
			System.out.println("SpecialEntityItem created at position X: "+event.entity.posX+", Y: "+event.entity.posY+", Z: "+event.entity.posZ);
			entityItem.setEntityItemStack(((EntityItem)event.entity).getEntityItem());
			System.out.println("event.entity has had its EntityItemStack set");
			//DEBUG
			System.out.println("Registering NBTTagCompound on " + entityItem.toString());
			NBTTagCompound nbt = new NBTTagCompound();
			//DEBUG
			System.out.println("nbt var created");
			event.entity.writeToNBTOptional(nbt);
			//DEBUG
			System.out.println("event.entity written to nbt");
			entityItem.readFromNBT(nbt);
			//DEBUG
			System.out.println("entityItem read from nbt");
			event.entity.worldObj.spawnEntityInWorld(entityItem);
			//DEBUG
			System.out.println("entityItem spawned");
		}
	}
}

 

 

 

Thank you everyone for their help. It has been a very interesting lesson ;D ;D

Posted

"I know Java"

30fac46e141074215b3c7c7341f68ca4.jpg

 

Do you know what is super.method() and why it exists? :)

 

Call it, don't copy whole method (onUpdate()).

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

Posted

I'm not a master of Java but I know my way around the language. I actually didn't think of that tbh... I feel dumb. Cuts down on code, thanks!

 

(I like the pic xD )

 

Also, I've only been learning Java for about 4 months so cut me some slack ;P When I say I know Java, I mean that I can work through the code and stuff. I don't know everything yet but I'm still learning as I go

Posted

Don' feel bad. When I came to MC modding in spring 2014, I had never seen a stitch of Java in my life (but I had done object-oriented  {O-O} design and programming in 3 other languages). Being unemployed at the time, I justified my modding effort as a learning experience for both Java and Eclipse (see my signature). It took me almost two weeks to write and debug my 1st basic mod (a new gem for the nether with tools and armor to suit). I blame conflicting tutorials and the jump from 1.6.4 to 1.7.2.

 

If nothing else, then get this:

 

1) Eclipse is your friend, especially when you use it to jump (visually) into the vanilla code referenced by your mod (you really want to have setup a  "decomp" workspace).

2) The debugger is also your friend, because it lets you see what is REALLY happening (no more guesswork!). I so deeply wish that every new modder would set break points and fire up the debugger before posting his/her 1st runtime "doesn't work" thread.

 

However, if one is new to more than Java... If one is not familiar with O-O design, then there is much more to learn. Java is merely a tool like many other tools (though reflection was new to me when I arrived). If you've already mastered O-O design in one or more other languages, then the basics of Java are a snap.

 

On the other hand, O-O design is a paradigm -- a kick-in-the-head, counter-intuitive thought process that is best acquired via mentoring (e.g. junior-college or better class with a good teacher/professor, or a real programming job with a good tech lead). If O-O design and coding (e.g. inheritance and run-time polymorphism) are new to you, then get help. Sign up for a class, or ask your boss for a mentor, and (to the reader finding this thread in the future) come back in a few months.

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.