Jump to content

Recommended Posts

Posted

So I am having a problem with my tileentity for a wind turbine I am working on, I have got the wind turbine in the game, it is rendered correctly, and I don't crash when using it (except for shift clicking items into it) but, when I place more than one in the world, two strange things happen, one: the turbine rotor spins faster (I know this is an issue with the TileEntityRendererWindTurbine.class, but I cant figure out what exactly the issue is) and two: the second wind turbine I place in the world has the same amount of power as the first one, and it doubles the output speed, if I add a third one, it triples the output speed and makes the rotor spin even faster. I think the wind turbine isn't creating a new tileentity when it is added, and it is using all the data from the first wind turbine, but even that is strange because the items aren't duplicated across all the wind turbines, they are only in the one I place them in, only power is.

 

Here is my code (Just ask me if you need to see any other relavent classes)

 

 

TileEntityWindTurbine.class

 

 

package net.theepictekkit.generator.common.tileentity;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.theepictekkit.generator.Generator;
import net.theepictekkit.generator.common.container.ContainerWindTurbine;
import net.theepictekkit.generator.common.energy.IEnergyGenerator;
import net.theepictekkit.generator.common.items.ItemHandler;

public class TileEntityWindTurbine extends TileEntity implements ISidedInventory, IEnergyGenerator {

public static float rotationAngle = 0;
public static float speed = 3.0F;
public static int worldHeight;
public static int weatherStrength;
public static float efficiency;


public static float output = 30.0F; //The energy being generated per rotation of the turbine;
public static float power = 0.0F; //The currently stored energy value
public static float generating = 0.0F; //The energy currently being generated
public static int bufferMax = 2560000; //The max energy the buffer can store
public static int outputMax = 8; //Can not generate more energy per tick than this (determined by the rotor type)
private static int rotorValue = 74;

public static int rotorType = 0;

public static boolean hasIronTurbine;
public static boolean hasSteelTurbine;
public static boolean hasCarbonTurbine;
public static boolean hasRotor;

public int direction;

public String inventoryName;

private ItemStack[] slots = new ItemStack[3];

public static ItemStack returnStackInSlot() {
	TileEntityWindTurbine tileEntity = new TileEntityWindTurbine();
	ItemStack itemStack = tileEntity.getStackInSlot(0);
	if (itemStack != null && itemStack.stackSize > 0) {
		return itemStack;
	} else {
		return null;
	}
}

public ItemStack getStackInSlot(int i) {
	return this.slots[i];
}

public void updateEntity() {

	if (this.getStackInSlot(0) != null) {
		if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorIron) {
			this.rotorType = 1;
		} else if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorSteel) {
			this.rotorType = 2;
		} else if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorCarbon) {
			this.rotorType = 3;
		}
		System.out.println(this.rotorType);
	} else {
		System.out.println("false");
		this.rotorType = 0;
	}
	if (this.rotorType > 0) {
		generating = output * speed * worldHeight / rotorValue;
		efficiency = (generating / outputMax) * 100;

		worldHeight = this.yCoord;

		rotationAngle += speed * worldHeight / 100;
		if (rotationAngle >= 360) {
			rotationAngle = 0;
		}


		power += output * speed * worldHeight / rotorValue;
		if (power > bufferMax) {
			power = bufferMax;
			this.generating = 0;
			this.efficiency = 0;
		}
		if (power != bufferMax && Generator.developmentMode == true) {
			System.out.println("Current energy stored in wind turbine located at X: " + this.xCoord + ", Y: " + this.yCoord + ", Z: " + this.zCoord + " is: " + this.power + "/" + this.bufferMax + "	Woops! must have accidently set to development mode. Please report this as a bug!");
		}
	} else {
		this.efficiency = 0;
		this.generating = 0;
	}
	/*ItemStack itemStack = this.getStackInSlot(0);

	if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorIron) {
		TileEntityRendererWindTurbine.instance.rotorType = 1;
	} if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorSteel) {
		this.hasRotor = true;
		TileEntityRendererWindTurbine.instance.rotorType = 2;
	} if (this.getStackInSlot(0).getItem() == ItemHandler.itemTurbineRotorCarbon) {
		this.hasRotor = true;
		TileEntityRendererWindTurbine.instance.rotorType = 3;
	} if (this.getStackInSlot(0).getItem() == null) {
		this.hasRotor = false;
		TileEntityRendererWindTurbine.instance.rotorType = 0;
	} else {
		this.hasRotor = false;
		TileEntityRendererWindTurbine.instance.rotorType = 1;
	}*/
}

public int getPowerScaled(int i) {
	return ((int)power * i / bufferMax);
}

public boolean isInvNameLocalized() {
	return this.inventoryName != null && this.inventoryName.length() > 0;
}

public void readFromNBT (NBTTagCompound nbt) {
	super.readFromNBT(nbt);

	NBTTagList nbtTagList = nbt.getTagList("Items", 10);
	this.slots = new ItemStack[this.getSizeInventory()];

	for (int i = 0; i < nbtTagList.tagCount(); i++) {
		NBTTagCompound nbt1 = (NBTTagCompound) nbtTagList.getCompoundTagAt(i);
		byte b0 = nbt1.getByte("Slot");

		if (b0 >= 0 && b0 < this.slots.length) {
			this.slots[b0] = ItemStack.loadItemStackFromNBT(nbt1);
		}
	}

	this.power = nbt.getShort("EnergyStored");

	if (nbt.hasKey("CustomName")) {
		this.inventoryName = nbt.getString("CustomName");
	}
}

public void writeToNBT (NBTTagCompound nbt) {
	super.writeToNBT(nbt);

	nbt.setShort(("EnergyStored"), (short)this.power);
	NBTTagList nbtTagList = new NBTTagList();

	for (int i = 0; i < this.slots.length; i++) {
		if (this.slots[i] != null) {
			NBTTagCompound nbtTagCompound = new NBTTagCompound();
			nbtTagCompound.setByte("Slot", (byte)i);
			this.slots[i].writeToNBT(nbtTagCompound);
			nbtTagList.appendTag(nbtTagCompound);
		}
	}

	nbt.setTag("Items", nbtTagList);

	if (this.isInvNameLocalized()) {
		nbt.setString("CustomName", this.inventoryName);
	}
}

public int maxOutput() {
	return this.outputMax;
}

public float currentOutput() {
	return this.output;
}

public int bufferSize() {
	return this.bufferMax;
}

public float bufferStored() {
	return this.power;
}

public boolean canPushEnergy() {
	return true;
}

public boolean stopIfFull() {
	return false;
}

public void getFuelValueFromItem(ItemStack item) {

}

public void onBufferOverload(int currentBufferStored, boolean isBufferFull) {

}

public int getSizeInventory() {
	return 64;
}

public ItemStack decrStackSize(int i, int j) {

	if (this.slots[i] != null) {
		ItemStack itemStack;
		if (this.slots[i].stackSize <= j) {
			itemStack = this.slots[i];
			this.slots[i] = null;
			return itemStack;
		} else {
			itemStack = this.slots[i].splitStack(j);

			if (this.slots[i].stackSize == 0) {
				this.slots[i] = null;
			}
		}
		return itemStack;
	}
	return null;
}

public ItemStack getStackInSlotOnClosing(int i) {
	if (this.slots[i] != null)  {
		ItemStack itemStack = this.slots[i];
		this.slots[i] = null;
		return itemStack;
	}
	return null;
}

public void setInventorySlotContents(int i, ItemStack itemStack) {

	this.slots[i] = itemStack;

	if (itemStack != null && itemStack.stackSize > this.getInventoryStackLimit())

		itemStack.stackSize = this.getInventoryStackLimit();
}

public String getInventoryName() {
	return this.hasCustomInventoryName() ? this.inventoryName : "container.furnace";
}

/**
 * Returns if the inventory is named
 */
public boolean hasCustomInventoryName()
{
	return this.inventoryName != null && this.inventoryName.length() > 0;
}

public void setGuiDisplayName(String str)
{
	this.inventoryName = str;
}

public int getInventoryStackLimit() {
	return 1;
}

public boolean isUseableByPlayer(EntityPlayer player) {
	return true;
}

public void openInventory() {

}

public void closeInventory() {

}

public static boolean isItemTurbine(ItemStack itemStack) {
	return itemStack.getItem() == ItemHandler.itemTurbineRotorIron ? true : (itemStack.getItem() == ItemHandler.itemTurbineRotorSteel ? true : (itemStack.getItem() == ItemHandler.itemTurbineRotorCarbon ? true : false));


}

public boolean isItemValidForSlot(int i, ItemStack itemStack) {
	return  i == 0 ? isItemTurbine(itemStack) : false;

}

public int[] getAccessibleSlotsFromSide(int p_94128_1_) {
	return null;
}

public boolean canInsertItem(int par1, ItemStack itemStack, int par3) {
	return this.isItemValidForSlot(par1, itemStack);
}

public boolean canExtractItem(int par1, ItemStack itemStack, int par3) {
	return par3 != 0 || par1 != 1;
}
}

 

 

 

TileEntityRendererWindTurbine.class

 

 

package net.theepictekkit.generator.client.blocks.renderer;

import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.theepictekkit.generator.Reference;
import net.theepictekkit.generator.common.blocks.model.*;
import net.theepictekkit.generator.common.tileentity.TileEntityWindTurbine;

import org.lwjgl.opengl.GL11;

public class TileEntityRendererWindTurbine extends TileEntitySpecialRenderer {

private static String modid = Reference.MODID;
protected static final ResourceLocation textureTurbine = new ResourceLocation("generator:textures/models/WindTurbine.png");
protected static final ResourceLocation textureRotor1 = new ResourceLocation("generator:textures/models/TurbineRotorIron.png");
protected static final ResourceLocation textureRotor2 = new ResourceLocation("generator:textures/models/TurbineRotorSteel.png");
protected static final ResourceLocation textureRotor3 = new ResourceLocation("generator:textures/models/TurbineRotorCarbon.png");

private modelWindTurbine modelTurbine;
private modelTurbineRotor modelRotor;

public static boolean doRenderRotor;

public static TileEntityRendererWindTurbine instance;

public int rotorType = 0;

public TileEntityRendererWindTurbine() {
	modelTurbine = new modelWindTurbine();
	modelRotor = new modelTurbineRotor();

	this.instance = this;
}


public void adjustRotatePivotViaMeta(World world, int x, int y, int z) {

}

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {

	TileEntityWindTurbine tileEntity1 = (TileEntityWindTurbine) tileEntity;

	//Turbine Main
	GL11.glPushMatrix();
	GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
	GL11.glRotatef(180, 0, 0, 1);
	Minecraft.getMinecraft().renderEngine.bindTexture(textureTurbine);
	GL11.glPushMatrix();
	this.modelTurbine.render((Entity)null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F);
	GL11.glPopMatrix();
	GL11.glPopMatrix();


	//Turbine Rotor
	if (TileEntityWindTurbine.rotorType > 0) {
		GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 8.75F, (float)z + 0.5F);

		TileEntityWindTurbine windTurbine = (TileEntityWindTurbine) tileEntity.getWorldObj().getTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord);
		GL11.glRotatef(TileEntityWindTurbine.rotationAngle, 0, 0, 1);

		if (TileEntityWindTurbine.rotorType == 1) {
			Minecraft.getMinecraft().renderEngine.bindTexture(textureRotor1);
		} else if (TileEntityWindTurbine.rotorType == 2) {
			Minecraft.getMinecraft().renderEngine.bindTexture(textureRotor2);
		} else if (TileEntityWindTurbine.rotorType == 3) {
			Minecraft.getMinecraft().renderEngine.bindTexture(textureRotor3);
		}
		GL11.glPushMatrix();
		this.modelRotor.render((Entity)null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F);
		GL11.glPopMatrix();
		GL11.glPopMatrix();
	}
}

public void adjustLightFixture(World world, int x, int y, int z, Block block) {
	Tessellator tessellator = Tessellator.instance;
	float brightness = block.getLightValue(world, x, y, z);
	int skyLight = world.getLightBrightnessForSkyBlocks(x, y, z, 0);
	int modifier = skyLight % 65536;
	int divModifier = skyLight / 65536;
	tessellator.setColorOpaque_F(brightness, brightness, brightness);
	OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)modifier, divModifier);
}
}

 

 

 

Oh, and another thing I would like to try and do and cant figure out is how to get the wind turbine to face the player, I know how to do this with a normal block, but it isn't working with the custom rendered block. I have tried to get the metadata of the block (because the orientation of the block is stored in metadata) and use that in a switch statement to rotate the model with GL11 in TileEntityRendererWindTurbine.class, but it didn't work.

 

Help would be much appreciated.

Thanks in advance

 

I ask complicated questions, and apparently like to write really long detailed posts. But I also help others when I can.

Posted

This is basic Java.

 

In Java (and other object-oriented languanges) whenever all of your instances are acting like they have the same value it means you're using static fields wrong.  You should study what static means.  Static means that all your instances will have the same value.

 

In you code you have the power levels static so all will have same power.

 

Just remove the static declaration and I think it should improve and maybe fix your problems.  Please also read about how static works to ensure you fully understand why this was a problem.

 

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

OK thankyou for your help.

 

now the energy and rotor speed is independent.

 

The reason I was using the static modifier was because other classes were referencing the tileEntityWindTurbine and was giving an error saying to change to static, so this now gives me another problem, things like rendering the rotor is now the same accross all turbines (I have 3 different types of rotors, and it renders the type in the inventory), I have created an instance of the wind turbines tileentity

TileEntityWindTurbine instance;

and made a constructer

public TileEntityWindTurbine() {
    this.instance = this;
}

 

so this seems to have fixed one problem, but created another.

 

Sorry if I seem like a bit of a noob to java, I am new to it.

 

oh, and right now, I am reading up about static modifiers (and some other stuff in java I don't understand)

I ask complicated questions, and apparently like to write really long detailed posts. But I also help others when I can.

Posted

You don't need the instance variable. You need to get the TileEntity in the render class using IBlockAccess#getTileEntity(x,y,z). That gives you a instance of the TileEntity which you can use for getting variables.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Posted

That's not a actual Java thing, it is used on the forums here to indicate that you need to call that method from a instance of that class, instead of directly like it was a static method.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Posted

Sorry, but I still don't understand, i cant figure out what to do, i cant add IBlockAccess to renderTileEntityAt like

public void renderTileEntityAt(IBlockAccess iblockAccess, TileEntity tileEntity, double x, double y, double z, float f) {...

so what do I do?

I ask complicated questions, and apparently like to write really long detailed posts. But I also help others when I can.

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

    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • 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() ); } }  
  • Topics

×
×
  • Create New...

Important Information

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