Jump to content

[Solved] [1.7.10] Adding velocity to entities onTick does nothing?


IceMetalPunk

Recommended Posts

I'm trying to simulate wind during rain in my mod. So I have a tick handler that's listening for the ServerTickEvent, and after a cooldown, it checks the world for rain, then iterates through all loaded entities and adds to their velocity. Sounds simple, right?

 

Except it's not doing anything. I put a debug message into the console logger to see what's going on, but the message looks fine: it tells me it's moving me with a random x or z amount between 1 and 4, just as it should be. But I don't actually move...nothing moves. Am I using the Entity#addVelocity() function incorrectly or something?

 

This is the code for the tick handler:

 

package com.IceMetalPunk.weatherworks;

import java.util.List;

import cpw.mods.fml.common.eventhandler.EventBus;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;

public class WeatherTickHandler {
private byte dir=0;
private float amt=1.0f;
private int cooldown=0;

public WeatherTickHandler(EventBus bus) {
	bus.register(this);;
}

@SubscribeEvent
public void onTick(ServerTickEvent event) {
	if (event.phase==Phase.START) {

		// Decrement the cooldown
		if (this.cooldown>0) { --this.cooldown; }

		// Only blow wind when cooldown<=40
		if (this.cooldown>40) { return; }

		World world=MinecraftServer.getServer().getEntityWorld();

		// Only blow wind when it's raining
		if (world.getWorldInfo().isRaining() || world.getWorldInfo().isThundering()) {

			// Calculate wind speed on x and z axes
			float velX=(this.dir==0)?this.amt:((this.dir==1)?-this.amt:0);
			float velZ=(this.dir==2)?this.amt:((this.dir==3)?-this.amt:0);

			// Iterate through the list of entities
			List entities=world.getLoadedEntityList();
			for (int p=0; p<entities.size(); ++p) {
				Entity ent=((Entity)entities.get(p));

				/* Debug message */
				if (ent instanceof EntityPlayerMP) {
					System.out.println("Moving "+ent+" by "+velX+", "+velZ);
				}
				/* End debug message */

				// Add the velocity to each entity
				ent.addVelocity(velX, 0.0d, velZ);
			}
		}

		// When cooldown=0, reset cooldown and choose a random direction and amount for next time
		if (this.cooldown==0) {
			this.cooldown=100;
			this.dir=(byte)world.rand.nextInt(4);
			this.amt=world.rand.nextFloat()*3.0f+1.0f;
		}
	}
}
}

Whatever Minecraft needs, it is most likely not yet another tool tier.

Link to comment
Share on other sites

Have you played with the scale of your wind velocity to calibrate it? Maybe you're adding a trivial amount.

 

If you keep adding velocity to already moving entities, won't they accelerate to great speeds?

 

And what will happen to minecarts? Paintings (and itemFrames)?

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.

Link to comment
Share on other sites

@thebest108: I tried that first, and it didn't work, either.

 

@jeffryfisher: I figured I'd deal with the special cases of "static" entities once I got the main system working. 4 blocks per second per second is certainly not trivial xD But they are, in fact, supposed to accelerate. Keep in mind it only happens for a short period of time each "gust" of wind, it's not constantly accelerating them.

 

@coolAlias: Aha! When it didn't work for the player, I kept trying to fix it without thinking to test other entities. It actually does work for other entities (I had to lower the amounts and timings to get something decent, but that's trivial). I didn't realize player motion was entirely client-side. I guess I'll have to implement a packet handler for this, then. I'll try that and see where it goes from there. Thanks!

 

*EDIT* Well...that made things worse. Now, when the wind starts, the game just locks up completely. The debug output tells me that, for some odd reason, even though the packet message instance is created with the proper x, y, and z velocity values, by the time the client receives it, it's reading ridiculously large (as in, on the order of 1E9) x and y values instead. I can't figure out why.

 

Here's the updated tick handler source:

package com.IceMetalPunk.weatherworks;

import java.util.List;

import cpw.mods.fml.common.eventhandler.EventBus;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;

public class WeatherTickHandler {
private byte dir=0;
private float amt=1.0f;
private int cooldown=0;
private final double threshold=20.0d;

public WeatherTickHandler(EventBus bus) {
	bus.register(this);;
}

@SubscribeEvent
public void onTick(ServerTickEvent event) {
	if (event.phase==Phase.START) {

		// Decrement the cooldown
		if (this.cooldown>0) { --this.cooldown; }

		// Only blow wind when cooldown<=40
		if (this.cooldown>this.threshold) { return; }

		World world=MinecraftServer.getServer().getEntityWorld();

		// Only blow wind when it's raining
		if (world.getWorldInfo().isRaining() || world.getWorldInfo().isThundering()) {

			// Calculate wind speed on x and z axes
			float velX=(this.dir==0)?this.amt:((this.dir==1)?-this.amt:0);
			float velZ=(this.dir==2)?this.amt:((this.dir==3)?-this.amt:0);

			// Iterate through the list of entities
			List entities=world.getLoadedEntityList();
			for (int p=0; p<entities.size(); ++p) {
				Entity ent=((Entity)entities.get(p));

				/* Debug message */
				if (ent instanceof EntityPlayerMP && this.cooldown==this.threshold) {
					System.out.println("Sending "+((double)(velX*this.threshold))+", "+(0.0d)+", "+((double)(velZ*this.threshold)));
					WeatherworksPacketHandler.INSTANCE.sendToAll(new WeatherManipMessage((byte)2, (double)(velX*this.threshold), 0.0d, (double)(velZ*this.threshold), (byte)0));
				}
				/* End debug message */

				// Add the velocity to each entity
				ent.addVelocity((double)velX, 0.0d, (double)velZ);
			}
		}

		// When cooldown=0, reset cooldown and choose a random direction and amount for next time
		if (this.cooldown==0) {
			this.cooldown=100;
			this.dir=(byte)world.rand.nextInt(4);
			this.amt=world.rand.nextFloat()/4.0f;
		}
	}
}
}

 

Here's the message class ("val" is there for other message types; it's irrelevant to this issue):

public class WeatherManipMessage implements IMessage {

public byte val=0;
public double x, y, z;
public byte messageType=0;

public WeatherManipMessage() {};

public WeatherManipMessage(byte type, double x, double y, double z, byte state) {
	this.val=state;
	this.x=x;
	this.y=y;
	this.z=z;
	this.messageType=type;
	System.out.println("Created message with "+this.x+", "+this.y+", "+this.z);
}

@Override
public void fromBytes(ByteBuf buf) {
	this.messageType=buf.readByte();
	this.x=buf.readInt();
	this.y=buf.readInt();
	this.z=buf.readInt();
	this.val=buf.readByte();
}

@Override
public void toBytes(ByteBuf buf) {
	buf.writeByte(this.messageType);
	buf.writeDouble(this.x);
	buf.writeDouble(this.y);
	buf.writeDouble(this.z);
	buf.writeByte(this.val);
}
}

 

Here's the message handler:

public static class WeatherWorksWindHandler implements IMessageHandler<WeatherManipMessage,IMessage> {

	@Override
	public IMessage onMessage(WeatherManipMessage message, MessageContext ctx) {
		if (message.messageType==2) {
			EntityPlayer player=Minecraft.getMinecraft().thePlayer;
			System.out.println("Moved "+player+" by "+(message.x)+", "+(message.y)+", "+(message.z));
			player.addVelocity(message.x, message.y, message.z);
		}
		return null;
	}

}

 

And here's the registration of the message handler, in the preinit event handler:

int messageID=0;
WeatherworksPacketHandler.INSTANCE.registerMessage(WeatherWorksWindHandler.class, WeatherManipMessage.class, messageID++, Side.CLIENT);

 

Given that, this is the strange output I'm getting in the console:

[15:47:14] [server thread/INFO] [sTDOUT]: [com.IceMetalPunk.weatherworks.WeatherTickHandler:onTick:51]: Sending 0.611920952796936, 0.0, 0.0
[15:47:14] [server thread/INFO] [sTDOUT]: [com.IceMetalPunk.weatherworks.WeatherManipMessage:<init>:26]: Created message with 0.611920952796936, 0.0, 0.0
[15:47:14] [Client thread/INFO] [sTDOUT]: [com.IceMetalPunk.weatherworks.WeatherManipMessage$WeatherWorksWindHandler:onMessage:84]: Moved EntityClientPlayerMP['Player703'/7, l='MpServer', x=582.96, y=57.62, z=-124.47] by 1.071879387E9, 1.073741824E9, 0.0

 

As you can see, the values it's sending are fine, the constructor is setting those values fine as well...but when the client receives the message, it's reading massive and incorrect values instead. I can't figure out why?

Whatever Minecraft needs, it is most likely not yet another tool tier.

Link to comment
Share on other sites

Gah! That worked! :D All this trouble with the packet handling, and it wasn't even necessary after all >_< Thank you so much!

Whatever Minecraft needs, it is most likely not yet another tool tier.

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

    • Try deliting feur builder  It caused this issue in my modpack
    • I am not using hardcoded recipes, I'm using Vanilla's already existing code for leather armor dying. (via extending and implementing DyeableArmorItem / DyeableLeatherItem respectively) I have actually figured out that it's something to do with registering item colors to the ItemColors instance, but I'm trying to figure out where exactly in my mod's code I would be placing a call to the required event handler. Unfortunately the tutorial is criminally undescriptive. The most I've found is that it has to be done during client initialization. I'm currently trying to do the necessary setup via hijacking the item registry since trying to modify the item classes directly (via using SubscribeEvent in the item's constructor didn't work. Class so far: // mrrp mrow - mcmod item painter v1.0 - catzrule ch package catzadvitems.init; import net.minecraft.client.color.item.ItemColors; import net.minecraft.world.item.Item; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.client.event.ColorHandlerEvent; import catzadvitems.item.DyeableWoolArmorItem; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class Painter { @ObjectHolder("cai:dyeable_wool_chestplate") public static final Item W_CHEST = null; @ObjectHolder("cai:dyeable_wool_leggings") public static final Item W_LEGS = null; @ObjectHolder("cai:dyeable_wool_boots") public static final Item W_SOCKS = null; public Painter() { // left blank, idk if forge throws a fit if constructors are missing, not taking the chance of it happening. } @SubscribeEvent public static void init(FMLClientSetupEvent event) { new Painter(); } @Mod.EventBusSubscriber private static class ForgeBusEvents { @SubscribeEvent public static void registerItemColors(ColorHandlerEvent.Item event) { ItemColors col = event.getItemColors(); col.register(DyeableUnderArmorItem::getItemDyedColor, W_CHEST, W_LEGS, W_SOCKS); //placeholder for other dye-able items here later.. } } } (for those wondering, i couldn't think of a creative wool helmet name)
    • nvm found out it was because i had create h and not f
    • Maybe there's something happening in the 'leather armor + dye' recipe itself that would be updating the held item texture?
    • @SubscribeEvent public static void onRenderPlayer(RenderPlayerEvent.Pre e) { e.setCanceled(true); model.renderToBuffer(e.getPoseStack(), pBuffer, e.getPackedLight(), 0f, 0f, 0f, 0f, 0f); //ToaPlayerRenderer.render(); } Since getting the render method from a separate class is proving to be bit of a brick wall for me (but seems to be the solution in older versions of minecraft/forge) I've decided to try and pursue using the renderToBuffer method directly from the model itself. I've tried this route before but can't figure out what variables to feed it for the vertexConsumer and still can't seem to figure it out; if this is even a path to pursue.  The vanilla model files do not include any form of render methods, and seem to be fully constructed from their layer definitions? Their renderer files seem to take their layers which are used by the render method in the vanilla MobRenderer class. But for modded entities we @Override this function and don't have to feed the method variables because of that? I assume that the render method in the extended renderer takes the layer definitions from the renderer classes which take those from the model files. Or maybe instead of trying to use a render method I should be calling the super from the renderer like   new ToaPlayerRenderer(context, false); Except I'm not sure what I would provide for context? There's a context method in the vanilla EntityRendererProvider class which doesn't look especially helpful. I've been trying something like <e.getEntity(), model<e.getEntity()>> since that generally seems to be what is provided to the renderers for context, but I don't know if it's THE context I'm looking for? Especially since the method being called doesn't want to take this or variations of this.   In short; I feel like I'm super super close but I have to be missing something obvious? Maybe this insane inane ramble post will provide some insight into this puzzle?
  • Topics

×
×
  • Create New...

Important Information

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