Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

How to perform an operation on the server side through the Event Handler?


Greyscail
 Share

Recommended Posts

I have this for my Event Handler class:

 

public class ModEventHandler
{
	@SubscribeEvent
	public static void dualWield(MouseEvent event)
	{
      	// bunch of code
      
      	boolean isSuccessfulAttack = target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);
      
      	// bunch of code
	}
}

 

Registered as follows:

 

@EventHandler
	public void preInit(FMLInitializationEvent event)
	{
		MinecraftForge.EVENT_BUS.register(ModEventHandler.class);
	}

 

Where I've basically copied the code minecraft uses when you left click except I've altered it to allow attacking with the offhand weapon. My issue is that the line of code responsible for actually doing the damage seemingly only works when called from the server side. I have no clue how to remedy this, I've tried putting:

 

public class ModEventHandler
{
	@SideOnly(Side.SERVER)
	@SubscribeEvent
	public static void dualWield(MouseEvent event)
	{
      	// bunch of code
      
      	boolean isSuccessfulAttack = target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);
      
      	// bunch of code
	}
}

 

But that just crashes. The issue I'm having is how should I call something from the server if it is running in my Event Handler?

Link to comment
Share on other sites

Just now, diesieben07 said:

You don't understand the difference between logical and physical side. Once again: read and understand the documentation. If you have questions, ask.

 

You need packets.

hehe, I'm just more of a learn by example type of person rather than the type to dig through an instruction manual, had I ever seen packets being used then I'd have probably figured that out sooner

Link to comment
Share on other sites

22 minutes ago, Greyscail said:

I have this for my Event Handler class:

 


public class ModEventHandler
{
	@SubscribeEvent
	public static void dualWield(MouseEvent event)
	{
      	// bunch of code
      
      	boolean isSuccessfulAttack = target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);
      
      	// bunch of code
	}
}

 

Registered as follows:

 


@EventHandler
	public void preInit(FMLInitializationEvent event)
	{
		MinecraftForge.EVENT_BUS.register(ModEventHandler.class);
	}

 

Where I've basically copied the code minecraft uses when you left click except I've altered it to allow attacking with the offhand weapon. My issue is that the line of code responsible for actually doing the damage seemingly only works when called from the server side. I have no clue how to remedy this, I've tried putting:

 


public class ModEventHandler
{
	@SideOnly(Side.SERVER)
	@SubscribeEvent
	public static void dualWield(MouseEvent event)
	{
      	// bunch of code
      
      	boolean isSuccessfulAttack = target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);
      
      	// bunch of code
	}
}

 

But that just crashes. The issue I'm having is how should I call something from the server if it is running in my Event Handler?

Some events are only read by the logical client, or logical server, or both, depending on the result of the event. Therefore, if only a client responds, you need to send packets to the logical server telling it to perform certain code that the client is not responsible for performing, like @diesieben07 mentioned.

NOTE: if you perform server-side code on client-side, it may not work... packets...

Edited by Differentiation
  • Like 1
Link to comment
Share on other sites

3 hours ago, Differentiation said:

Some events are only read by the logical client, or logical server, or both, depending on the result of the event. Therefore, if only a client responds, you need to send packets to the logical server telling it to perform certain code that the client is not responsible for performing, like @diesieben07 mentioned.

NOTE: if you perform server-side code on client-side, it may not work... packets...

 

Ok I've set all that up and works to an extent except the problem hasn't been solved, I have:

 

boolean isSuccessfulAttack = target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);

System.out.println(Thread.currentThread().getName());

 

And the console says Server Thread but target.attackEntiityFrom() still returns false

Link to comment
Share on other sites

30 minutes ago, Greyscail said:

target.attackEntityFrom(DamageSource.causePlayerDamage(player), damage)

Is this a boolean statement?

 

Can you please show us ALL the code you have so that we can help?

 

You might also want to incorporate this code to check for the running side:

public class SideTest //Not the name I recommend, nor do I have this name, but incorporate the below method in some class...
{
	public static void getSide(World worldIn)
	{
		if (worldIn.isRemote)
		{
    			System.out.println("CLIENT");
		}

		if (!worldIn.isRemote)
		{
          		System.out.println("SERVER"); //These show as the color RED in the client as info, so it's easy to see!
		}
    	}
}

 

And then where ever you want to test for the side, you call this static method.

 

This is how I test the running thread on my mod.

 

 

If the server is NOT running, then the boolean statement will not run and will automatically return false since the server did not read it, of course. Then this means that you need to send a packet to the server.

 

I hope I made things a bit more clear!

Try what I told you, then respond with the results :)

 

If you're still having trouble

 

Oh, and lastly, please don't use @SideOnly(Side.SERVER) or @SideOnly(Side.CLIENT), they don't help in this context.

Edited by Differentiation
Link to comment
Share on other sites

1 minute ago, Differentiation said:

Is this a boolean statement?

 

Can you please show us ALL the code you have so that we can help?

 

You might also want to incorporate this code to check for the running side:


if (worldIn.isRemote)
{
    System.out.println("CLIENT");
}

if (!worldIn.isRemote)
{
    System.out.println("SERVER");
}

 

If the server is NOT running, then the boolean statement will not run and will automatically return false since the server did not read it, of course. Then this means that you need to send a packet to the server.

 

I hope I made things a bit more clear!

Try what I told you, then respond with the results :)

 

And lastly, please don't use @SideOnly(Side.SERVER) or @SideOnly(Side.CLIENT), they don't help in this context.

 

Yea it's a boolean, and I'm hesitant to show all of my code because it'd be a huge mess with how spread out it is. And yea, it definitely says client side using the method showed me which is annoying because I'm certain I set the message system up properly and it definitely says Server Thread when I ran:

 

System.out.println(Thread.currentThread().getName());
Link to comment
Share on other sites

1 minute ago, Greyscail said:

 

Yea it's a boolean, and I'm hesitant to show all of my code because it'd be a huge mess with how spread out it is. And yea, it definitely says client side using the method showed me which is annoying because I'm certain I set the message system up properly and it definitely says Server Thread when I ran:

 


System.out.println(Thread.currentThread().getName());

I mean, my method would, in this case, be more accurate... and, since you're getting false for the boolean, and the fact that my method says CLIENT, then only the client runs, which means you need to start sending packets!

  • Like 1
Link to comment
Share on other sites

public class ModEventHandler
{
	private static final int LMB = 0, RMB = 1;

	private static enum WEAPON
	{
		ItemSword, ItemAxe
	}

	@SubscribeEvent
	public void dualWield(MouseEvent event)
	{
		if (event.isButtonstate())
		{
			Minecraft minecraft = Minecraft.getMinecraft();

			EntityPlayerSP player = minecraft.player;

			ItemStack mainhand = player.getHeldItem(EnumHand.MAIN_HAND);
			ItemStack offhand = player.getHeldItem(EnumHand.OFF_HAND);

			String primaryType = mainhand.getItem().getClass().getSimpleName();
			String secondaryType = offhand.getItem().getClass().getSimpleName();

			try
			{
				WEAPON.valueOf(primaryType);
				WEAPON.valueOf(secondaryType);
			}
			catch (IllegalArgumentException e)
			{
				return;
			}

			if (event.getButton() == RMB)
			{
				if (!minecraft.player.isRowingBoat())
				{
					switch (minecraft.objectMouseOver.typeOfHit)
					{
					case ENTITY:

						// minecraft.playerController.attackEntity(player,
						// minecraft.objectMouseOver.entityHit);

						// minecraft.playerController.syncCurrentPlayItem();

						if (minecraft.playerController.getCurrentGameType() != GameType.SPECTATOR)
						{
							AttackHandler.attackQueue.add(new Attack(player, minecraft.objectMouseOver.entityHit));

							ExampleMod.INSTANCE.registerMessage(ModMessageHandler.class, ModMessage.class, ExampleMod.id++, Side.SERVER);
							ExampleMod.INSTANCE.sendToServer(new ModMessage(ModMessageHandler.DO_ATTACK));
						}

						break;

					case BLOCK:

						BlockPos blockpos = minecraft.objectMouseOver.getBlockPos();

						if (!minecraft.world.isAirBlock(blockpos))
						{
							minecraft.playerController.clickBlock(blockpos, minecraft.objectMouseOver.sideHit);

							break;
						}

					case MISS:

						minecraft.player.resetCooldown();

						net.minecraftforge.common.ForgeHooks.onEmptyLeftClick(player);
					}
				}

				player.setActiveHand(EnumHand.OFF_HAND);
				player.swingArm(EnumHand.OFF_HAND);
			}
		}
	}
}
public class ModMessageHandler implements IMessageHandler<ModMessage, IMessage>
{
	public static final int DO_ATTACK = 0;
	
	@Override
	public IMessage onMessage(ModMessage message, MessageContext ctx)
	{
		EntityPlayerMP serverPlayer = ctx.getServerHandler().player;

		int code = message.code;

		serverPlayer.getServerWorld().addScheduledTask(() ->
		{
			switch (code)
			{
			case DO_ATTACK:

				AttackHandler.attack();
				
				break;

			default:

				break;
			}
		});

		return null;
	}
}
public class AttackHandler
{
	public static final ArrayList<Attack> attackQueue = new ArrayList<Attack>();

	public static void attack()
	{
		Attack attack = attackQueue.get(0);

		attack(attack.getAttacker(), attack.getAttacked());

		attackQueue.remove(0);
	}

	public static void attack(EntityPlayer player, Entity target)
	{
		if (!net.minecraftforge.common.ForgeHooks.onPlayerAttackTarget(player, target)) return;
		if (target.canBeAttackedWithItem())
		{
			if (!target.hitByEntity(player))
			{
				float damage = (float) player.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue();
				float enchantmentModifier;

				if (target instanceof EntityLivingBase)
				{
					enchantmentModifier = EnchantmentHelper.getModifierForCreature(player.getHeldItem(EnumHand.OFF_HAND), ((EntityLivingBase) target).getCreatureAttribute());
				}
				else
				{
					enchantmentModifier = EnchantmentHelper.getModifierForCreature(player.getHeldItem(EnumHand.OFF_HAND), EnumCreatureAttribute.UNDEFINED);
				}

				float swingModifier = player.getCooledAttackStrength(0.5F);

				damage *= (0.2F + swingModifier * swingModifier * 0.8F);
				enchantmentModifier *= swingModifier;

				player.resetCooldown();

				if (damage > 0.0F || enchantmentModifier > 0.0F)
				{
					boolean isFullSwing = swingModifier > 0.9F;
					boolean isKnockbackStrike = false;

					int knockbackLevel = EnchantmentHelper.getKnockbackModifier(player);

					if (player.isSprinting() && isFullSwing)
					{
						player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_KNOCKBACK, player.getSoundCategory(), 1.0F, 1.0F);

						++knockbackLevel;

						isKnockbackStrike = true;
					}

					boolean isCriticalStrike = isFullSwing && player.fallDistance > 0.0F && !player.onGround && !player.isOnLadder() && !player.isInWater() && !player.isPotionActive(MobEffects.BLINDNESS) && !player.isRiding() && target instanceof EntityLivingBase;

					// isCriticalStrike = isCriticalStrike && !player.isSprinting();
					isCriticalStrike &= !player.isSprinting();

					net.minecraftforge.event.entity.player.CriticalHitEvent hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(player, target, isCriticalStrike, isCriticalStrike ? 1.5F : 1.0F);

					isCriticalStrike = hitResult != null;

					if (isCriticalStrike)
					{
						damage *= hitResult.getDamageModifier();
					}

					damage = damage + enchantmentModifier;

					boolean isSweepingStrike = false;

					double d0 = (double) (player.distanceWalkedModified - player.prevDistanceWalkedModified);

					if (isFullSwing && !isCriticalStrike && !isKnockbackStrike && player.onGround && d0 < (double) player.getAIMoveSpeed())
					{
						ItemStack itemstack = player.getHeldItem(EnumHand.OFF_HAND);

						if (itemstack.getItem() instanceof ItemSword)
						{
							isSweepingStrike = true;
						}
					}

					float targetHealth = 0.0F;

					boolean hasSetFire = false;

					int fireaspectModifier = EnchantmentHelper.getFireAspectModifier(player);

					if (target instanceof EntityLivingBase)
					{
						targetHealth = ((EntityLivingBase) target).getHealth();

						if (fireaspectModifier > 0 && !target.isBurning())
						{
							hasSetFire = true;

							target.setFire(1);
						}
					}

					double d1 = target.motionX;
					double d2 = target.motionY;
					double d3 = target.motionZ;

					if (target.getEntityWorld().isRemote)
					{
					    System.out.println("CLIENT");
					}

					if (!target.getEntityWorld().isRemote)
					{
					    System.out.println("SERVER");
					}
					
					boolean isSuccessfulAttack = ((EntityLivingBase) target).attackEntityFrom(DamageSource.causePlayerDamage(player), damage);

					target.performHurtAnimation();

					if (isSuccessfulAttack)
					{
						if (knockbackLevel > 0)
						{
							if (target instanceof EntityLivingBase)
							{
								((EntityLivingBase) target).knockBack(player, (float) knockbackLevel * 0.5F, (double) MathHelper.sin(player.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(player.rotationYaw * 0.017453292F)));
							}
							else
							{
								target.addVelocity((double) (-MathHelper.sin(player.rotationYaw * 0.017453292F) * (float) knockbackLevel * 0.5F), 0.1D, (double) (MathHelper.cos(player.rotationYaw * 0.017453292F) * (float) knockbackLevel * 0.5F));
							}

							player.motionX *= 0.6D;
							player.motionZ *= 0.6D;
							player.setSprinting(false);
						}

						if (isSweepingStrike)
						{
							float areaDamage = 1.0F + EnchantmentHelper.getSweepingDamageRatio(player) * damage;

							for (EntityLivingBase entitylivingbase : player.world.getEntitiesWithinAABB(EntityLivingBase.class, target.getEntityBoundingBox().grow(1.0D, 0.25D, 1.0D)))
							{
								if (entitylivingbase != player && entitylivingbase != target && !player.isOnSameTeam(entitylivingbase) && player.getDistanceSqToEntity(entitylivingbase) < 9.0D)
								{
									entitylivingbase.knockBack(player, 0.4F, (double) MathHelper.sin(player.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(player.rotationYaw * 0.017453292F)));
									entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage(player), areaDamage);
								}
							}

							player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_SWEEP, player.getSoundCategory(), 1.0F, 1.0F);
							player.spawnSweepParticles();
						}

						if (target instanceof EntityPlayerMP && target.velocityChanged)
						{
							((EntityPlayerMP) target).connection.sendPacket(new SPacketEntityVelocity(target));
							target.velocityChanged = false;
							target.motionX = d1;
							target.motionY = d2;
							target.motionZ = d3;
						}

						if (isCriticalStrike)
						{
							player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_CRIT, player.getSoundCategory(), 1.0F, 1.0F);
							player.onCriticalHit(target);
						}

						if (!isCriticalStrike && !isSweepingStrike)
						{
							if (isFullSwing)
							{
								player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_STRONG, player.getSoundCategory(), 1.0F, 1.0F);
							}
							else
							{
								player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_WEAK, player.getSoundCategory(), 1.0F, 1.0F);
							}
						}

						if (enchantmentModifier > 0.0F)
						{
							player.onEnchantmentCritical(target);
						}

						player.setLastAttackedEntity(target);

						if (target instanceof EntityLivingBase)
						{
							EnchantmentHelper.applyThornEnchantments((EntityLivingBase) target, player);
						}

						EnchantmentHelper.applyArthropodEnchantments(player, target);

						ItemStack weapon = player.getHeldItem(EnumHand.OFF_HAND);

						Entity entity = target;

						if (target instanceof MultiPartEntityPart)
						{
							IEntityMultiPart ientitymultipart = ((MultiPartEntityPart) target).parent;

							if (ientitymultipart instanceof EntityLivingBase)
							{
								entity = (EntityLivingBase) ientitymultipart;
							}
						}

						if (!weapon.isEmpty() && entity instanceof EntityLivingBase)
						{
							ItemStack beforeHitCopy = weapon.copy();
							weapon.hitEntity((EntityLivingBase) entity, player);

							if (weapon.isEmpty())
							{
								net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, beforeHitCopy, EnumHand.OFF_HAND);
								player.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY);
							}
						}

						if (target instanceof EntityLivingBase)
						{
							float f5 = targetHealth - ((EntityLivingBase) target).getHealth();
							player.addStat(StatList.DAMAGE_DEALT, Math.round(f5 * 10.0F));

							if (fireaspectModifier > 0)
							{
								target.setFire(fireaspectModifier * 4);
							}

							if (player.world instanceof WorldServer && f5 > 2.0F)
							{
								int k = (int) ((double) f5 * 0.5D);
								((WorldServer) player.world).spawnParticle(EnumParticleTypes.DAMAGE_INDICATOR, target.posX, target.posY + (double) (target.height * 0.5F), target.posZ, k, 0.1D, 0.0D, 0.1D, 0.2D);
							}
						}

						player.addExhaustion(0.1F);
					}
					else
					{
						player.world.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_NODAMAGE, player.getSoundCategory(), 1.0F, 1.0F);

						if (hasSetFire)
						{
							target.extinguish();
						}
					}
				}
			}
		}
	}

	public static class Attack
	{
		EntityPlayer attacker;
		Entity attacked;

		public Attack(EntityPlayer attacker, Entity attacked)
		{
			this.attacker = attacker;
			this.attacked = attacked;
		}

		public EntityPlayer getAttacker()
		{
			return attacker;
		}

		public Entity getAttacked()
		{
			return attacked;
		}
	}
}

 

@Differentiation Erm that's my code I really don't know what's wrong... :(

 

Link to comment
Share on other sites

1 minute ago, Differentiation said:

This is client-side. Server code does not read from here on.

But I thought it wouldn't matter since that was all from before:

 

AttackHandler.attackQueue.add(new Attack(player, minecraft.objectMouseOver.entityHit));

ExampleMod.INSTANCE.registerMessage(ModMessageHandler.class, ModMessage.class, ExampleMod.id++, Side.SERVER);
ExampleMod.INSTANCE.sendToServer(new ModMessage(ModMessageHandler.DO_ATTACK));

 

I thought everything before that wouldn't matter

Link to comment
Share on other sites

Just now, Differentiation said:

What do you mean "before that"? Your code is clearly mixed there!

I still don't get it, how is it mixed? The only line of code that I'm having issues with is:

 

boolean isSuccessfulAttack = ((EntityLivingBase) target).attackEntityFrom(DamageSource.causePlayerDamage(player), damage);

 

And I was told that it needed to be called from the server side. The way you're making it sound is like everything I wrote needs to be called from the server side. For one, the first class where the bulk of the code is, is my Event Handler so I couldn't make that server side even if I wanted to

Link to comment
Share on other sites

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
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • I keep getting the following error when I try to start up minecraft. Brief report: I already tried to uninstall forge and download it again, uninstall the mods and download others, I changed the version (before 1.17.1 to 1.18.1), I already deleted the phrase "forge-common.toml of type COMMON for modid forge" and even saving it magically returned to the report.  I also put the crash report here.
    • Hello, I'm trying to make a forge server for me and a few friends to play on. Generally this goes over without too many problems but just recently when i was trying to make a new modpack the server wouldnt start, so I went through removing mods until I could find the error and as it turned out no mods were erroring, as just lone forge wouldnt start. the error I seem to be getting is "19.01 21:59:37 [Server] INFO ERROR StatusLogger Reconfiguration failed: No configuration found for '232204a1' at 'null' in 'null'" I have no idea what this means but after this the console wont send any messages other than "Auto-saving world..." after a couple minutes, and when out of curiosity I tried to join on a client it acted like the server was up but I could not join and there was no response console side from me trying to do so. It does recieve stop and start commands fine though. Thank you
    • Any help or advice would be appreciated. I'm trying to learn how to add particles to a mod, using a tutorial from TheGreyGhost. Trying to get the particle to appear in the Entity's tick() method. The vanilla FLAME particle appears but not my particle. @Override public void tick() { if(entity == null) return; try { // Adds a particle to every entity while in the overworld! //this.level.addParticle(ParticleTypes.FLAME, this.getX(), this.getY() + 1, this.getZ(), 0, 0.04, 0); // Try to add a custom particle to every entity in the overworld. Color tint = Color.CYAN; // does this do anything if the particle texture is already colored? double diameter = this.getEntityScale(); FlameParticleData flameParticleData = new FlameParticleData(tint, diameter); this.level.addParticle(flameParticleData, this.getX(), this.getY() + 2, this.getZ(), 0, 0.05, 0); } catch (Exception e) { The other code I have setting up the Particle Registration, the FlameParticle, the FlameParticleData, the FlameParticleFactory, and the FlameParticleType: ParticleRegistration.java. I also have a flame_particle.json that references the flame.png that I want to use. @Mod.EventBusSubscriber(modid = MyMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class ParticleRegistration { public static final DeferredRegister<ParticleType<?>> PARTICLES_TYPES = DeferredRegister.create( ForgeRegistries.PARTICLE_TYPES, MyMod.MODID); // This sets the FlameParticleType to use the textures specified in flame_particle.json. public static final RegistryObject<ParticleType<FlameParticleData>> FLAME_PARTICLE = PARTICLES_TYPES.register( "flame_particle", FlameParticleType::new); // Is this necessary? public static ParticleType<FlameParticleData> flameParticleType = new FlameParticleType(); @SuppressWarnings("resource") @SubscribeEvent public static void registerParticleFactory(ParticleFactoryRegisterEvent event) { Minecraft.getInstance().particleEngine.register(ParticleRegistration.FLAME_PARTICLE.get(), FlameParticleFactory::new); } } FlameParticle.java /** * Based on TheGreyGhost's MinecraftByExample * Custom Particle to illustrate how to add a Particle with your own texture and movement/animation behaviour * */ public class FlameParticle extends SpriteTexturedParticle { /** * Construct a new FlameParticle at the given [x,y,z] position, with the given initial velocity, the given color, and the * given diameter. * We also supply sprites so that you can change the sprite texture in the tick() method (although not needed for this example) */ public FlameParticle(ClientWorld world, double x, double y, double z, double velocityX, double velocityY, double velocityZ, Color tint, double diameter, IAnimatedSprite sprites) { super(world, x, y, z, velocityX, velocityY, velocityZ); this.sprites = sprites; setColor(tint.getRed()/255.0F, tint.getGreen()/255.0F, tint.getBlue()/255.0F); setSize((float)diameter, (float)diameter); // the size (width, height) of the collision box. final float PARTICLE_SCALE_FOR_ONE_METRE = 0.5F; // if the particleScale is 0.5, the texture will be rendered as 1 metre high // sets the rendering size of the particle for a TexturedParticle. this.scale(PARTICLE_SCALE_FOR_ONE_METRE * (float)diameter); //maxAge = 100; // lifetime in ticks: 100 ticks = 5 seconds this.lifetime = 100; final float ALPHA_VALUE = 1.0F; this.alpha = ALPHA_VALUE; //the vanilla Particle constructor added random variation to our starting velocity. Undo it! this.xd = velocityX; this.yd = velocityY; this.zd = velocityZ; // the move() method will check for collisions with scenery this.hasPhysics = true; // I think hasPhysics replaces canCollide } // Comments from TheGreyGhost // ---- methods used by TexturedParticle.renderParticle() method to find out how to render your particle // the base method just renders a quad, rotated to directly face the player // can be used to change the skylight+blocklight brightness of the rendered Particle. @Override public int getLightColor(float partialTick) // previously protected int getBrightnessForRender(float partialTick) { final int BLOCK_LIGHT = 15; // maximum brightness final int SKY_LIGHT = 15; // maximum brightness final int FULL_BRIGHTNESS_VALUE = LightTexture.pack(BLOCK_LIGHT, SKY_LIGHT); // .pack replaces .packLight return FULL_BRIGHTNESS_VALUE; // if you want the brightness to be the local illumination (from block light and sky light) you can just use // the Particle.getBrightnessForRender() base method, which contains: // BlockPos blockPos = new BlockPos(this.posX, this.posY, this.posZ); // return this.world.isBlockLoaded(blockPos) ? WorldRenderer.getCombinedLight(this.world, blockPos) : 0; } // Choose the appropriate render type for your particles: // There are several useful predefined types: // PARTICLE_SHEET_TRANSLUCENT semi-transparent (translucent) particles // PARTICLE_SHEET_OPAQUE opaque particles // TERRAIN_SHEET particles drawn from block or item textures // PARTICLE_SHEET_LIT appears to be the same as OPAQUE. Not sure of the difference. In previous versions of minecraft, // "lit" particles changed brightness depending on world lighting i.e. block light + sky light public IParticleRenderType getRenderType() { return IParticleRenderType.PARTICLE_SHEET_TRANSLUCENT; } /** * call once per tick to update the Particle position, calculate collisions, remove when max lifetime is reached, etc */ @Override public void tick() { // if you want to change the texture as the particle gets older, you can use //setSpriteFromAge(sprites); // not sure whether this should be uncommented yet this.xo = x; // previously prevPosX and posX this.yo = y; // previously prevPosY and posY this.xo = z; // previously prevPosZ and posZ move(xd, yd, zd); // simple linear motion. You can change speed by changing xd, yd, // zd every tick. For example - you can make the particle accelerate downwards due to gravity by // final double GRAVITY_ACCELERATION_PER_TICK = -0.02; // yd += GRAVITY_ACCELERATION_PER_TICK; // calling move() also calculates collisions with other objects // collision with a block makes the ball disappear. But does not collide with entities if (onGround) { // onGround is only true if the particle collides while it is moving downwards... this.remove(); // this.setExpired() is probably this.remove() } if (yo == y && yd > 0) { // detect a collision while moving upwards (can't move up at all) this.remove(); } if (this.age++ >= this.lifetime) { // this.maxAge becomes this.lifetime this.remove(); } } private final IAnimatedSprite sprites; // contains a list of textures; choose one using either // newParticle.selectSpriteRandomly(sprites); or newParticle.selectSpriteWithAge(sprites); } FlameParticleData.java /** * Based on TheGreyGhost's MinecraftByExample * The particle has two pieces of information which are used to customise it: * * 1) The colour (tint) which is used to change the hue of the particle * 2) The diameter of the particle * * This class is used to * 1) store this information, and * 2) transmit it between server and client (write and read methods), and * 3) parse it from a command string i.e. the /particle params */ public class FlameParticleData implements IParticleData { public FlameParticleData(Color tint, double diameter) { this.tint = tint; this.diameter = constrainDiameterToValidRange(diameter); } public Color getTint() { return tint; } /** * @return get diameter of particle in metres */ public double getDiameter() { return diameter; } @Nonnull @Override public ParticleType<FlameParticleData> getType() { return ParticleRegistration.flameParticleType; } // write the particle information to a PacketBuffer, ready for transmission to a client @Override public void writeToNetwork(PacketBuffer buf) { buf.writeInt(tint.getRed()); buf.writeInt(tint.getGreen()); buf.writeInt(tint.getBlue()); buf.writeDouble(diameter); } // used for debugging I think; prints the data in human-readable format @Nonnull @Override public String writeToString() { return String.format(Locale.ROOT, "%s %.2f %i %i %i", this.getType().getRegistryName(), diameter, tint.getRed(), tint.getGreen(), tint.getBlue()); } private static double constrainDiameterToValidRange(double diameter) { final double MIN_DIAMETER = 0.05; final double MAX_DIAMETER = 1.0; return MathHelper.clamp(diameter, MIN_DIAMETER, MAX_DIAMETER); } private Color tint; private double diameter; // Comments from the TheGreyGhost // --------- these remaining methods are used to serialize the Particle Data. // I'm not yet sure what the Codec is used for, given that the DESERIALIZER already deserializes using read. // Perhaps it will be used to replace the manual read methods in the future. // The CODEC is a convenience to make it much easier to serialise and deserialise your objects. // Using the builder below, you construct a serialiser and deserialiser in one go, using lambda functions. // eg for the FlameParticleData CODEC: // a) In order to serialise it, it reads the 'tint' member variable (type: INT) and the 'diameter' member variable (type: DOUBLE) // b) In order to deserialise it, call the matching constructor FlameParticleData(INT, DOUBLE) public static final Codec<FlameParticleData> CODEC = RecordCodecBuilder.create( instance -> instance.group( Codec.INT.fieldOf("tint").forGetter(d -> d.tint.getRGB()), Codec.DOUBLE.fieldOf("diameter").forGetter(d -> d.diameter) ).apply(instance, FlameParticleData::new) ); private FlameParticleData(int tintRGB, double diameter) { this.tint = new Color(tintRGB); this.diameter = constrainDiameterToValidRange(diameter); } // The DESERIALIZER is used to construct FlameParticleData from either command line parameters or from a network packet public static final IDeserializer<FlameParticleData> DESERIALIZER = new IDeserializer<FlameParticleData>() { // parse the parameters for this particle from a /particle command @Nonnull @Override public FlameParticleData fromCommand(@Nonnull ParticleType<FlameParticleData> type, @Nonnull StringReader reader) throws CommandSyntaxException { reader.expect(' '); double diameter = constrainDiameterToValidRange(reader.readDouble()); final int MIN_COLOUR = 0; final int MAX_COLOUR = 255; reader.expect(' '); int red = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); reader.expect(' '); int green = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); reader.expect(' '); int blue = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); Color color = new Color(red, green, blue); return new FlameParticleData(color, diameter); } // read the particle information from a PacketBuffer after the client has received it from the server @Override public FlameParticleData fromNetwork(@Nonnull ParticleType<FlameParticleData> type, PacketBuffer buf) { // warning! never trust the data read in from a packet buffer. final int MIN_COLOUR = 0; final int MAX_COLOUR = 255; int red = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); int green = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); int blue = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); Color color = new Color(red, green, blue); double diameter = constrainDiameterToValidRange(buf.readDouble()); return new FlameParticleData(color, diameter); } }; } FlameParticleFactory.java /** * Based on TheGreyGhost's MinecraftByExample * On the client side: * When the client wants to spawn a Particle, it gives the FlameParticleData to this factory method * The factory selects an appropriate Particle class and instantiates it * */ public class FlameParticleFactory implements IParticleFactory<FlameParticleData> { //IParticleFactory private final IAnimatedSprite sprites; // contains a list of textures; choose one using either // not sure if i still need this // newParticle.selectSpriteRandomly(sprites); or newParticle.selectSpriteWithAge(sprites); // this method is needed for proper registration of your Factory: // The ParticleManager.register method creates a Sprite and passes it to your factory for subsequent use when rendering, then // populates it with the textures from your textures/particle/xxx.json public FlameParticleFactory(IAnimatedSprite sprite) { this.sprites = sprite; } @Nullable @Override public Particle createParticle(FlameParticleData flameParticleData, ClientWorld world, double xPos, double yPos, double zPos, double xVelocity, double yVelocity, double zVelocity) { FlameParticle newParticle = new FlameParticle(world, xPos, yPos, zPos, xVelocity, yVelocity, zVelocity, flameParticleData.getTint(), flameParticleData.getDiameter(), sprites); newParticle.pickSprite(sprites); // not quite the newParticle.selectSpriteRandomly(sprites) that was used. return newParticle; } // This is private to prevent you accidentally registering the Factory using the default constructor. // ParticleManager has two register methods, and if you use the wrong one the game will enter an infinite loop private FlameParticleFactory() { throw new UnsupportedOperationException("Use the FlameParticleFactory(IAnimatedSprite sprite) constructor"); } } FlameParticleType.java /** * Based on TheGreyGhost's MinecraftByExample * Simple class used to describe the Particle */ public class FlameParticleType extends ParticleType<FlameParticleData> { private static boolean ALWAYS_SHOW_REGARDLESS_OF_DISTANCE_FROM_PLAYER = false; public FlameParticleType() { super(ALWAYS_SHOW_REGARDLESS_OF_DISTANCE_FROM_PLAYER, FlameParticleData.DESERIALIZER); } // get the Codec used to // a) convert a FlameParticleData to a serialised format // b) construct a FlameParticleData object from the serialised format public Codec<FlameParticleData> codec() { return FlameParticleData.CODEC; } } The flame_particle.json, which is located in resources/asset.MyMod/particles, that references the flame.png, located in resources/asset.MyMod/particles/textures/particles { "textures": [ "MyMod:flame" ] }  
    • How did you figure out the texture changing? I looked at your code and I can't seem to replicate your solution.
    • Forge won't launch on minecraft 1.16.5  I already used --add-exports=java.base/sun.security.util=ALL-UNNAMED --add-opens=java.base/java.util.jar=ALL-UNNAMED and didn't work, I also tried changing my JMV to C:\Program Files\Java\jre1.8.0_321\bin\javaw.exe, C:\Program Files\Java\jre1.8.0_321\bin\java.exe, C:\Program Files\Java\jre1.8.0_321\bin\java.exe and didn't work and my Java version is 8 This is my error log  System info:   Operating system:     OSFullName: Microsoft Windows 10 Home Single Language     Build: 9200     Is64BitOperatingSystem: True   Java path: 'C:\Program Files\Java\jre1.8.0_321' (64-bit) Process info:   Minecraft version/type: 1.16.5-forge-36.2.20/release   Executable file: 'C:\Program Files\Java\jre1.8.0_321\bin\javaw.exe'   Arguments: '-XX:+IgnoreUnrecognizedVMOptions --add-exports=java.base/sun.security.util=ALL-UNNAMED --add-exports=jdk.naming.dns/com.sun.jndi.dns=java.naming --add-opens=java.base/java.util.jar=ALL-UNNAMED -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump "-Dos.name=Windows 10" -Dos.version=10.0 -Djava.library.path=C:\Users\agatt\AppData\Roaming\.minecraft\natives -Dminecraft.launcher.brand="Minecraft Launcher" -Dminecraft.launcher.version=3.9.5_. -cp C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\forge\1.16.5-36.2.20\forge-1.16.5-36.2.20.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm\9.1\asm-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-commons\9.1\asm-commons-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-tree\9.1\asm-tree-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-util\9.1\asm-util-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-analysis\9.1\asm-analysis-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\cpw\mods\modlauncher\8.0.9\modlauncher-8.0.9.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\cpw\mods\grossjava9hacks\1.3.3\grossjava9hacks-1.3.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\accesstransformers\3.0.1\accesstransformers-3.0.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\antlr\antlr4-runtime\4.9.1\antlr4-runtime-4.9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\eventbus\4.0.0\eventbus-4.0.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\forgespi\3.2.0\forgespi-3.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\coremods\4.0.6\coremods-4.0.6.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\unsafe\0.2.0\unsafe-0.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\electronwill\night-config\core\3.6.3\core-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\electronwill\night-config\toml\3.6.3\toml-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\jline\jline\3.12.1\jline-3.12.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\maven\maven-artifact\3.6.3\maven-artifact-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\jodah\typetools\0.8.3\typetools-0.8.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-api\2.15.0\log4j-api-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.15.0\log4j-core-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-slf4j18-impl\2.15.0\log4j-slf4j18-impl-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecrell\terminalconsoleappender\1.2.0\terminalconsoleappender-1.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\5.0.4\jopt-simple-5.0.4.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\spongepowered\mixin\0.8.4\mixin-0.8.4.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\nashorn-core-compat\15.1.1.1\nashorn-core-compat-15.1.1.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\patchy\1.3.9\patchy-1.3.9.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\dev\jna\jna\4.4.0\jna-4.4.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\ibm\icu\icu4j\66.1\icu4j-66.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\javabridge\1.0.22\javabridge-1.0.22.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\5.0.3\jopt-simple-5.0.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\io\netty\netty-all\4.1.25.Final\netty-all-4.1.25.Final.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\google\guava\guava\21.0\guava-21.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-io\commons-io\2.5\commons-io-2.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-codec\commons-codec\1.10\commons-codec-1.10.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\brigadier\1.0.17\brigadier-1.0.17.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\datafixerupper\4.0.26\datafixerupper-4.0.26.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\google\code\gson\gson\2.8.0\gson-2.8.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\authlib\2.1.28\authlib-2.1.28.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\it\unimi\dsi\fastutil\8.2.1\fastutil-8.2.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-api\2.8.1\log4j-api-2.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.8.1\log4j-core-2.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\3.2.2\lwjgl-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-jemalloc\3.2.2\lwjgl-jemalloc-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-openal\3.2.2\lwjgl-openal-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-opengl\3.2.2\lwjgl-opengl-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-glfw\3.2.2\lwjgl-glfw-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-stb\3.2.2\lwjgl-stb-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-tinyfd\3.2.2\lwjgl-tinyfd-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\3.2.2\lwjgl-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-jemalloc\3.2.2\lwjgl-jemalloc-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-openal\3.2.2\lwjgl-openal-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-opengl\3.2.2\lwjgl-opengl-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-glfw\3.2.2\lwjgl-glfw-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-tinyfd\3.2.2\lwjgl-tinyfd-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-stb\3.2.2\lwjgl-stb-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\text2speech\1.11.3\text2speech-1.11.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\text2speech\1.11.3\text2speech-1.11.3-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\versions\1.16.5\1.16.5.jar cpw.mods.modlauncher.Launcher --launchTarget fmlclient --fml.forgeVersion 36.2.20 --fml.mcVersion 1.16.5 --fml.forgeGroup net.minecraftforge --fml.mcpVersion 20210115.111550 --username zach --version "Minecraft Launcher" --gameDir C:\Users\agatt\AppData\Roaming\.minecraft --assetsDir C:\Users\agatt\AppData\Roaming\.minecraft\assets --assetIndex 1.16 --uuid d61616c3e2a6cf59a0cc435a66c091d4    Exit code: 1 //Finished printing debug information ============    
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.