Jump to content

[1.10.2] [SOLVED] Spawning particles in onBlockActivated


Recommended Posts

Posted (edited)

I want to spawn some fire particles in my block's onBlockActivated method, when a variable in my tile entity is the right value (basically, you have to "activate" the block 3 times within a small window of time before the particles will spawn, and I'm saving the number of times and time elapsed in my tile entity). I have read about a million posts on this, and everything says that you should be able to spawn vanilla particles from the server. I swear I have seen examples of other mods doing this, too, but I can't get it to work. I know the code is running, because the println statement fires.

 

I also tried sending a packet, but it didn't work. I didn't include that code since I don't really think I should have to do that anyway. Please correct me if I'm wrong.

 

I also tried spawning the particles on the client, but even after grabbing a copy of my tile entity from the BlockPos parameter, I can't seem to access the variables (they don't change like they should).

 

@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)
{
	EnumCampfireState campfireState = state.getValue(CAMPFIRE_STATE);
	TileEntity tileEntity = world.getTileEntity(pos);
	int stokeTime = ((PrimalTileEntityCampfire) tileEntity).tinderStokeTime;
	int timesBlown = ((PrimalTileEntityCampfire) tileEntity).tinderTimesBlown;

	if (world.isRemote) // client
	{
	// do stuff
	}
	else // server
	{			
		if (heldItem == null && campfireState == EnumCampfireState.TINDER_STOKED)
		{
			if (stokeTime < 40)
			{
				((PrimalTileEntityCampfire) tileEntity).tinderStokeTime = 60;
				((PrimalTileEntityCampfire) tileEntity).tinderTimesBlown += 1;
				PrimalPacketHandler.INSTANCE.sendTo(new PrimalCampfirePacket(player, 0, pos), (EntityPlayerMP) player);
			}
			if (timesBlown > 3)
			{
				System.out.println("Spawning particle");
				world.spawnParticle(EnumParticleTypes.FLAME, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), 0.0D, 0.0D, 0.0D, new int[0]);
			}			
		}			
	}
	return true;
}

 

Edited by Daeruin
  • Like 1
Posted (edited)

What version are you using? If it's the latest, you are not overriding onBlockActivated, as there is an extra ItemStack parameter. You should be overriding

public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { return false; }

which you can find in the Block class.

Edited by TheMasterGabriel
Posted

I'm using 1.10.2, as stated in the post title. Pretty sure my override is fine, as my version of Block shows this:

    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)

 

Posted

That's a good idea, but in this case the block is basically transparent. When I put that exact same call in the block's randomDisplayTick method, I can see the particles just fine.

Posted
2 hours ago, Daeruin said:

I'm using 1.10.2, as stated in the post title

 

Whoops, I don't know how I missed that. Apologies

 

From past experience, I'm fairly sure that particles only exist on the client, which is why you are not seeing them. Block#randomDisplayTick fires only on the client side, so it makes sense that you could see them there. Try spawning them on the client side. As for your variable problem, that is also due to the client/server side. In order for tile entity to recognize the variable changes on the client-side, you need to update the number of right clicks on the server side and then send the update to the client-side via a packet. You can read about networking and the side stuff on the Forge docs here.

Posted

World#spawnParticle(EnumParticleTypes, double, double, double, double, double, double, int...) does nothing on the server, it only spawns particles when called on the client. You need to use one of the spawnParticle overloads from WorldServer instead.

  • Like 1

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

I have read tutorials and other posts on this forum stating that you can initiate a particle on the server, using world#spawnParticle, and the server will automatically send out the required packets. For example:

 

http://jabelarminecraft.blogspot.com/p/minecraft-forge-1721710-modding-tips.html

 

Quote

Tip: Initiate the spawn of vanilla particles on the server side,. Even though EntityFX is only a client side class, the server method doesn't instantiate it but rather sends a packet to all the clients (which then instantiate the class). Since you usually want all players to see the particles, the method to initiate the spawn should be invoked on the server side (world.obj.isRemote should be false). 

 

I have done a few packets before, but it bugs me to go to that effort when a single line method call should work.

 

I already tried sending a packet to spawn the particle directly on the client, and it didn't work. It will play the sound correctly, and the println statements appear, but it won't spawn the particle. Here's the packet:

 

Spoiler

public class PrimalCampfirePacket implements IMessage
{

	private int playerId;
	private int messageId;
	private double posX;
	private double posY;
	private double posZ;

	public PrimalCampfirePacket()
	{
	}

	public PrimalCampfirePacket(EntityPlayer player, int messageId, BlockPos pos)
	{
		this.playerId = player.getEntityId();
		this.messageId = messageId;
		this.posX = pos.getX() + 0.5D;
		this.posY = pos.getY();
		this.posZ = pos.getZ() + 0.5D;
	}

	@Override
	public void fromBytes(ByteBuf buffer)
	{
		this.playerId = buffer.readInt();
		this.messageId = buffer.readInt();
		this.posX = buffer.readInt();
		this.posY = buffer.readInt();
		this.posZ = buffer.readInt();
	}

	@Override
	public void toBytes(ByteBuf buffer)
	{
		buffer.writeInt(playerId);
		buffer.writeInt(messageId);
		buffer.writeDouble(posX);
		buffer.writeDouble(posY);
		buffer.writeDouble(posZ);
	}

	public static class PrimalCampfireHandler implements IMessageHandler<PrimalCampfirePacket, IMessage>
	{

		@Override
		public IMessage onMessage(final PrimalCampfirePacket message, final MessageContext ctx)
		{
			IThreadListener mainThread = Minecraft.getMinecraft();
			mainThread.addScheduledTask(new Runnable()
			{
				@Override
				public void run()
				{
					Entity entity = Minecraft.getMinecraft().world.getEntityByID(message.playerId);
					System.out.println("Packet entity: " + entity);
					System.out.println("Packet messageId: " + message.messageId);
					if (entity instanceof EntityPlayer)
					{
						if (message.messageId == 0)
						{
							System.out.println("Packet playing sound");
							((EntityPlayer) entity).playSound(PrimalSoundRegistry.blowing, 1.0F, 1.0F);
						}
						if (message.messageId == 1)
						{
							System.out.println("Packet spawning flame");
							Minecraft.getMinecraft().world.spawnParticle(EnumParticleTypes.FLAME, message.posX, message.posY, message.posZ, 0.0D, 0.0D, 0.0D, new int[0]);
						}
					}
				}
			});
			return null;
		}

	}

}

 

 

Posted
12 minutes ago, Choonster said:

World#spawnParticle(EnumParticleTypes, double, double, double, double, double, double, int...) does nothing on the server, it only spawns particles when called on the client. You need to use one of the spawnParticle overloads from WorldServer instead.

 

Ninja'd. How do I do that? Do I cast my world parameter to WorldServer?

(On the server side, naturally - !world.isRemote)

Posted (edited)

In your code, you already check if you are on the server side. Because of that, you can cast your world object to a WorldServer object and then use the following method to spawn your particles. It's much easier than the manual packet thing (which I wouldn't have told you about if I'm not oblivious and had read the WorldServer class). Well, knowledge of packets is always good anyways :P

 

/** Spawns the desired particle and sends the necessary packets to the relevant connected players. */
public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int... particleArguments)

 

Edited by TheMasterGabriel
  • Like 2

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

    • that happens every time I enter a new dimension.
    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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