Jump to content

[UNSOLVED] [1.12.2] Making onItemRightClick(...) fire every tick?


Recommended Posts

Posted (edited)

Hey,

 

I'm trying to make the method onItemRightClick(...) in Item run every tick for a certain item of mine instead of every 4 ticks. Is there any way (or alternative way) I could do this?

 

Any help is appreciated. :)

Thanks!

Edited by Differentiation
Posted (edited)
34 minutes ago, Differentiation said:

Hey,

 

I'm trying to make the method onItemRightClick(...) in Item run every tick for a certain item of mine instead of every 4 ticks. Is there any way (or alternative way) I could do this?

 

Any help is appreciated. :)

Thanks!

Have a look at this thread.

Diesieben07 has explained clearly.

https://www.minecraftforge.net/forum/topic/76564-1122-onitemrightclick

Edited by poopoodice
Posted
11 minutes ago, Differentiation said:

Thanks for the response. Unfortunately, since only the server thread runs on onUsingTick() method (and since this method never even fires every tick I right-click for some reason), I'll do just fine with the onItemRightClick().

Actually, I use Mouse.isButtonDown(1) to represent right-click in the onUpdate() method. It works well for me but there might be some problems that I haven't notice.

Posted
1 hour ago, poopoodice said:

It works well for me but there might be some problems that I haven't notice.

You're reaching across logical sides and it wont work in multiplayer.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted (edited)

Is there a reason why onUsingTick() is never calling? :S

 

Also, is there a method for both server and client threads that runs every tick when the player right clicks without having to send packets?

 

Thanks!

Edited by Differentiation
Posted
17 minutes ago, diesieben07 said:

Show your code.

 

onUsingTick is that method, at least for your own items. Is that not what you need?

I'll send it when I get home.

 

I'm making a gun that fires rapidly (maybe every two ticks) so I need a method that runs on the server and client. The reason for the client is bc I'm making the player recoil every time they fire. 

Posted (edited)
50 minutes ago, diesieben07 said:

No.

You have now stated "i need it on the client" twice. And both times I responded: Yes, onUsingTick does that.

Well, I tested and world.isRemote returns false :S

 

Do I have to return a success for action result on both sides or something or is this method independent of onItemRightClick()?

Edited by Differentiation
Posted (edited)
4 hours ago, diesieben07 said:

Not sure what to say, looking at the code there is no reason for it to not be calld on the client.

Show your code.

package dinocraft.item;

import dinocraft.Reference;
import dinocraft.capabilities.entity.DinocraftEntity;
import dinocraft.entity.EntityRayBullet;
import dinocraft.init.DinocraftItems;
import dinocraft.init.DinocraftSoundEvents;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;

public class ItemRayGun extends Item
{
	public ItemRayGun(String name)
	{
		this.setUnlocalizedName(name);
		this.setMaxStackSize(1);
		this.setMaxDamage(1000);
		this.setRegistryName(new ResourceLocation(Reference.MODID, name));
	}
	
	@Override
	public void onUsingTick(ItemStack stack, EntityLivingBase entityliving, int count)
	{
		EntityPlayer player = (EntityPlayer) entityliving;
		DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
		
		if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
		{
			if (!player.isCreative())
			{
				dinoEntity.consumeAmmo(DinocraftItems.RAY_BULLET, 1);
				stack.damageItem(1, player);
			}
			
			if (!player.world.isRemote)
			{
				EntityRayBullet ball = new EntityRayBullet(player, 0.001F);
				ball.shoot(player, player.rotationPitch, player.rotationYaw, 0.0F, 15.0F, 0.0F);
				ball.setRotationYawHead(player.rotationYawHead);
				Vec3d vector = player.getLookVec();
				double x = vector.x;
				double y = vector.y;
				double z = vector.z;
				ball.motionX = x * 3.33D;
				ball.motionZ = z * 3.33D;
				ball.motionY = y * 3.33D;
				ball.setPositionAndUpdate(player.posX - (x * 0.75D), player.posY + player.eyeHeight, player.posZ - (z * 0.75D));
				player.world.spawnEntity(ball);
				player.world.playSound(null, player.getPosition(), DinocraftSoundEvents.RAY_GUN_SHOT, SoundCategory.NEUTRAL, 3.0F, player.world.rand.nextFloat() + 0.5F);
			}
            
			DinocraftEntity.getEntity(player).recoil(0.1F, 1.25F, true);
		}
		
		super.onUsingTick(stack, player, count);
	}
	
	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand)
	{
		ItemStack stack = player.getHeldItem(hand);
		DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
		
		if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
		{	
			player.setActiveHand(hand);
			return ActionResult.newResult(EnumActionResult.SUCCESS, stack);
		}
		else if (!world.isRemote)
		{
			dinoEntity.sendActionbarMessage(TextFormatting.RED + "Out of ammo!");
			world.playSound(null, player.getPosition(), SoundEvents.BLOCK_DISPENSER_DISPENSE, SoundCategory.NEUTRAL, 0.5F, 5.0F);
			return ActionResult.newResult(EnumActionResult.FAIL, stack);
		}
		
		return ActionResult.newResult(EnumActionResult.FAIL, stack);
	}
}

The onUsingTick method doesn't call at all when I right-click. :/

Edited by Differentiation
Posted
2 minutes ago, diesieben07 said:

You need to override Item#getUseDuration and specify a positive max-use duration in ticks.

I tried overriding Item::getMaxUseDuration and it still didn't call, I'm not sure if this is the one you're talking about.

Posted (edited)
2 hours ago, diesieben07 said:

Yes, I accidentally looked at the 1.14.4 method.

 

What did you return from getMaxUseDuration?

I tested it again using 0 and the onUsingTick method still doesn't happen.

 

I don't think I have to call it anywhere for it to work, right? This method shoul call when I use the item... but it just doesn't...

Edited by Differentiation
Posted
1 hour ago, diesieben07 said:

0 is not positive.

 

It fires but... once every 4 ticks again. I call setActiveHand in onItemRightClick. I tried calling it in onUpdate but that only runs on the client thread. Now it's kind of confusing. Where should I call setActiveHand?

Posted (edited)
10 minutes ago, diesieben07 said:

I really don't know what you are doing that you are getting it to fire every 4 ticks only. Every 4 ticks is what vanilla does for it's particle spawning, but onUsingTick is called outside of that, directly in EntityLivingBase#updateActiveHand, which is called directly from EntityLivingBase#onUpdate.

public class ItemRayGun extends Item
{
	public ItemRayGun(String name)
	{
		this.setUnlocalizedName(name);
		this.setMaxStackSize(1);
		this.setMaxDamage(1000);
		this.setRegistryName(new ResourceLocation(Reference.MODID, name));
	}
	
	@Override
	public int getMaxItemUseDuration(ItemStack stack)
	{
		return 1;
	}
	
	@Override
	public void onUsingTick(ItemStack stack, EntityLivingBase entityliving, int count)
	{
		EntityPlayer player = (EntityPlayer) entityliving;
		DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
		
		if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
		{
			if (!player.isCreative())
			{
				dinoEntity.consumeAmmo(DinocraftItems.RAY_BULLET, 1);
				stack.damageItem(1, player);
			}
			
			if (!player.world.isRemote)
			{
				EntityRayBullet ball = new EntityRayBullet(player, 0.001F);
				ball.shoot(player, player.rotationPitch, player.rotationYaw, 0.0F, 15.0F, 0.0F);
				ball.setRotationYawHead(player.rotationYawHead);
				Vec3d vector = player.getLookVec();
				double x = vector.x;
				double y = vector.y;
            	double z = vector.z;
            	ball.motionX = x * 3.33D;
            	ball.motionZ = z * 3.33D;
            	ball.motionY = y * 3.33D;
            	ball.setPositionAndUpdate(player.posX - (x * 0.75D), player.posY + player.eyeHeight, player.posZ - (z * 0.75D));
            	player.world.spawnEntity(ball);
            	player.world.playSound(null, player.getPosition(), DinocraftSoundEvents.RAY_GUN_SHOT, SoundCategory.NEUTRAL, 3.0F, player.world.rand.nextFloat() + 0.5F);
			}
            
			DinocraftEntity.getEntity(player).recoil(0.1F, 1.25F, true);
		}
		
		super.onUsingTick(stack, player, count);
	}
	
	@Override
	public void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected)
	{

		if (isSelected)
		{

			EntityPlayer player = (EntityPlayer) entity;
			DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
					
			if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
			{
				Item mainhand = player.getHeldItemMainhand().getItem();
				
				if (mainhand != null && mainhand == this)
				{
					player.setActiveHand(EnumHand.MAIN_HAND);
				}
				else
				{
					player.setActiveHand(EnumHand.OFF_HAND);
				}
			}
			else if (!world.isRemote)
			{
				dinoEntity.sendActionbarMessage(TextFormatting.RED + "Out of ammo!");
				world.playSound(null, player.getPosition(), SoundEvents.BLOCK_DISPENSER_DISPENSE, SoundCategory.NEUTRAL, 0.5F, 5.0F);
			}
					
			super.onUpdate(stack, world, entity, itemSlot, isSelected);
		}
	}
}

I noticed that onUsingTick only fires every tick if I explicitly call setActiveHand in onUpdate every tick... onUsingTick doesn't have anything to do with me right-clicking or using the item. That's what is so confusing to me.

Edited by Differentiation
Posted (edited)
41 minutes ago, diesieben07 said:

I really don't know what you are doing that you are getting it to fire every 4 ticks only. Every 4 ticks is what vanilla does for it's particle spawning, but onUsingTick is called outside of that, directly in EntityLivingBase#updateActiveHand, which is called directly from EntityLivingBase#onUpdate.

I tried running the code in onPlayerStoppedUsing and it's just a mess (fires sometimes on server thread, sometimes on client, idek anymore) it's very buggy and doesn't abide by getMaxItemUseDuration for shit. Anyways, I give up because it's way to hard to understand how the methods work together and I'm not stressing myself over something that's not even that important.

Edited by Differentiation
Posted (edited)
3 hours ago, Differentiation said:

I tested it again using 0 and the onUsingTick method still doesn't happen.

 

I don't think I have to call it anywhere for it to work, right? This method shoul call when I use the item... but it just doesn't...

getMaxItemUseDuration In Bow class returns 72000 which means you can hold the bow for 3600 seconds. 0 means the longest time you can use the item is 0 tick, it doesn't make sense. 

 

Edited by poopoodice
Posted
On 10/8/2019 at 7:22 PM, diesieben07 said:

This means your item may only be used for 1 tick before the usage gets cancelled.

I doubt you want this.

Okay so this is what I have.

public class ItemRayGun extends Item
{
	public ItemRayGun(String name)
	{
		this.setUnlocalizedName(name);
		this.setMaxStackSize(1);
		this.setMaxDamage(1000);
		this.setRegistryName(new ResourceLocation(Reference.MODID, name));
	}
	
	@Override
	public int getMaxItemUseDuration(ItemStack stack)
	{
		return 72000;
	}
	
	@Override
	public EnumAction getItemUseAction(ItemStack stack)
	{
		return EnumAction.BOW;
	}
	
	@Override
	public void onUsingTick(ItemStack stack, EntityLivingBase entityliving, int count)
	{
		if (entityliving.ticksExisted % 2 == 0)
		{
			EntityPlayer player = (EntityPlayer) entityliving;
			World world = player.world;
			DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
			
			DinocraftServer.getSide(world);
			
			if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
			{
				if (!player.isCreative())
				{
					dinoEntity.consumeAmmo(DinocraftItems.RAY_BULLET, 1);
					stack.damageItem(1, player);
				}
	        	
				if (!world.isRemote)
				{
					EntityRayBullet ball = new EntityRayBullet(player, 0.001F);
					Vec3d vector = player.getLookVec();
					double x = vector.x;
					double y = vector.y;
		        	double z = vector.z;
					ball.shoot(player, player.rotationPitch, player.rotationYaw, 0.0F, 3.33F, 0.0F);
					ball.setRotationYawHead(player.rotationYawHead);
		        	ball.setPositionAndUpdate(player.posX - (x * 0.75D), player.posY + player.eyeHeight, player.posZ - (z * 0.75D));
		        	world.spawnEntity(ball);
		        	world.playSound(null, player.getPosition(), DinocraftSoundEvents.RAY_GUN_SHOT, SoundCategory.NEUTRAL, 3.0F, world.rand.nextFloat() + 0.5F);
				}
		        
				DinocraftEntity.getEntity(player).recoil(0.1F, 1.25F, true);
			}
			else if (!world.isRemote)
			{
				dinoEntity.sendActionbarMessage(TextFormatting.RED + "Out of ammo!");
				world.playSound(null, player.getPosition(), SoundEvents.BLOCK_DISPENSER_DISPENSE, SoundCategory.NEUTRAL, 0.5F, 5.0F);
			}
			
			super.onUsingTick(stack, player, count);
		}
	}
	
	@Override
	public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
	{
		playerIn.setActiveHand(EnumHand.MAIN_HAND);
		return super.onItemRightClick(worldIn, playerIn, handIn);
	}
}

All goes well, but when I stop right-clicking, sometimes, the server thread doesn't get notified and it keeps running onUsingTick even though I'm not right clicking. The client side doesn't have this bug.

Also, when this fires, I get the following errors continuously. Not sure what they mean.

[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error in class 'ChannelLWJGL OpenAL'
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Invalid enumerated parameter value.
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error in class 'ChannelLWJGL OpenAL'
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error creating buffers in method 'preLoadBuffers'

 

  • Like 1
Posted (edited)
14 minutes ago, Differentiation said:

Okay so this is what I have.


public class ItemRayGun extends Item
{
	public ItemRayGun(String name)
	{
		this.setUnlocalizedName(name);
		this.setMaxStackSize(1);
		this.setMaxDamage(1000);
		this.setRegistryName(new ResourceLocation(Reference.MODID, name));
	}
	
	@Override
	public int getMaxItemUseDuration(ItemStack stack)
	{
		return 72000;
	}
	
	@Override
	public EnumAction getItemUseAction(ItemStack stack)
	{
		return EnumAction.BOW;
	}
	
	@Override
	public void onUsingTick(ItemStack stack, EntityLivingBase entityliving, int count)
	{
		if (entityliving.ticksExisted % 2 == 0)
		{
			EntityPlayer player = (EntityPlayer) entityliving;
			World world = player.world;
			DinocraftEntity dinoEntity = DinocraftEntity.getEntity(player);
			
			DinocraftServer.getSide(world);
			
			if (player.isCreative() || dinoEntity.hasAmmo(DinocraftItems.RAY_BULLET))
			{
				if (!player.isCreative())
				{
					dinoEntity.consumeAmmo(DinocraftItems.RAY_BULLET, 1);
					stack.damageItem(1, player);
				}
	        	
				if (!world.isRemote)
				{
					EntityRayBullet ball = new EntityRayBullet(player, 0.001F);
					Vec3d vector = player.getLookVec();
					double x = vector.x;
					double y = vector.y;
		        	double z = vector.z;
					ball.shoot(player, player.rotationPitch, player.rotationYaw, 0.0F, 3.33F, 0.0F);
					ball.setRotationYawHead(player.rotationYawHead);
		        	ball.setPositionAndUpdate(player.posX - (x * 0.75D), player.posY + player.eyeHeight, player.posZ - (z * 0.75D));
		        	world.spawnEntity(ball);
		        	world.playSound(null, player.getPosition(), DinocraftSoundEvents.RAY_GUN_SHOT, SoundCategory.NEUTRAL, 3.0F, world.rand.nextFloat() + 0.5F);
				}
		        
				DinocraftEntity.getEntity(player).recoil(0.1F, 1.25F, true);
			}
			else if (!world.isRemote)
			{
				dinoEntity.sendActionbarMessage(TextFormatting.RED + "Out of ammo!");
				world.playSound(null, player.getPosition(), SoundEvents.BLOCK_DISPENSER_DISPENSE, SoundCategory.NEUTRAL, 0.5F, 5.0F);
			}
			
			super.onUsingTick(stack, player, count);
		}
	}
	
	@Override
	public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
	{
		playerIn.setActiveHand(EnumHand.MAIN_HAND);
		return super.onItemRightClick(worldIn, playerIn, handIn);
	}
}

All goes well, but when I stop right-clicking, sometimes, the server thread doesn't get notified and it keeps running onUsingTick even though I'm not right clicking. The client side doesn't have this bug.

Also, when this fires, I get the following errors continuously. Not sure what they mean.


[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error in class 'ChannelLWJGL OpenAL'
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Invalid enumerated parameter value.
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error in class 'ChannelLWJGL OpenAL'
[22:01:36] [Thread-6/ERROR] [minecraft/SoundManager]: Error creating buffers in method 'preLoadBuffers'

 

Hello me again lol.

This should solve your first problem.

Edited by poopoodice
  • Thanks 1
Posted (edited)
8 hours ago, poopoodice said:

Hello me again lol.

This should solve your first problem.

I don't believe that Item::damageItem() changes my ItemStack... :/

 

doesn't it just... damage the current ItenStack?

Edited by Differentiation

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

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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