Jump to content

[1.12.1]TileEntity how do I sync data between server and client


Recommended Posts

Posted

Hi, I'm still working on the portals for my botania addon, This time, the problem is that data is not syncing between the server and client. when I activate a portal - you can go through it, but none of the animations show up.

here is my source code:

Spoiler

package mods.giantnuker.botaniatweaks.tile;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Nonnull;

import mods.giantnuker.backslash.RandUtil;
import mods.giantnuker.backslash.block.Schematic;
import mods.giantnuker.backslash.block.Schematic.StatePos;
import mods.giantnuker.backslash.block.SchematicUtil;
import mods.giantnuker.botaniatweaks.BTConfig;
import mods.giantnuker.botaniatweaks.BTMod;
import mods.giantnuker.botaniatweaks.block.BlockPortalCore;
import mods.giantnuker.javautil.Pair;
import mods.giantnuker.javautil.PairList;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeChunkManager;
import vazkii.botania.api.state.BotaniaStateProps;
import vazkii.botania.api.state.enums.AlfPortalState;
import vazkii.botania.api.state.enums.LivingRockVariant;
import vazkii.botania.api.state.enums.LivingWoodVariant;
import vazkii.botania.api.wand.IWandBindable;
import vazkii.botania.client.core.handler.HUDHandler;
import vazkii.botania.common.Botania;
import vazkii.botania.common.block.ModBlocks;

public class TilePortalCore extends TilePylonUser implements ITickable, IWandBindable {
	public BlockPos boundTo;
	public AlfPortalState state = AlfPortalState.OFF;
	public static ForgeChunkManager.Ticket chunkloadTicket;
	public int ticksOpen;
	public List<Entity> inPortal = new ArrayList();
	public boolean depower;
	public static final Schematic shape = new Schematic().add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
			new BlockPos(-1, 0, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(1, 0, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(2, 1, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-2, 1, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(2, 3, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-2, 3, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-1, 4, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(1, 4, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.FRAMED), 
					new BlockPos(-2, 2, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.FRAMED), 
					new BlockPos(2, 2, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.PATTERN_FRAMED), 
					new BlockPos(0, 4, 0))
			.add(BTMod.dreamyPortal.getDefaultState(), new BlockPos(0, 0, 0))
			.add(SchematicUtil.getRect(Blocks.AIR.getDefaultState(), new BlockPos(2, 2, 0)).modToPos(new BlockPos(-1, 1, 0)))
			.cleanup();
	@Override
	public void update() {
		if (world.getBlockState(getPos()) == null) return;
		if (this.getStateByShape() == AlfPortalState.OFF) {
			severConnection();
			if (getBound() != null)getBound().severConnection();
			return;
		}
		updateState();
		if(state == AlfPortalState.OFF) {
			ticksOpen = 0;
			pylon_act = TileCrystalPylon.EnumActivation.OFF;
		} else if (depower) {
			if (getBound() != null)getBound().depower = true;
			if (ticksOpen > 100) ticksOpen = 100;
			if (ticksOpen < 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_IN) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_IN;
				updatePylons();
			}
			giveMana(BTConfig.portalInitCost / 150);
			ticksOpen--;
			if (ticksOpen <= 0) {
				if (pylon_act != TileCrystalPylon.EnumActivation.OFF) {
					pylon_act = TileCrystalPylon.EnumActivation.OFF;
					updatePylons();
				}
				depower = false;
				setState(true, false);
				chunkload(false);
			}
		} else if (ticksOpen < 80) {
			if (ticksOpen < 1)world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ENTITY_GUARDIAN_ATTACK, SoundCategory.BLOCKS, 5, 5, true);
			if (ticksOpen < 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_OUT;
				updatePylons();
			} else if (ticksOpen > 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_LIGHTSWIRL_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_LIGHTSWIRL_OUT;
				updatePylons();
			}
			ticksOpen++;
			int use = useMana(BTConfig.portalInitCost / 80);
			if (use > 0) {
				pylon_act = TileCrystalPylon.EnumActivation.OFF;
				updatePylons();
				for (int i = 0; i < 10; i++) {
					blockParticle();
				}
			}
		} else {
			state = getStateByShape();
			if (pylon_act != TileCrystalPylon.EnumActivation.SWIRLING_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.SWIRLING_OUT;
				updatePylons();
			}
			ticksOpen++;
			if (getBound() == null) {
				severConnection();
				setState(false, false);
				return;
			} else {
				List<Entity> ents = world.getEntitiesWithinAABB(Entity.class, getTeleportAABB());
				List<Entity> entsp = world.getEntitiesWithinAABB(Entity.class, getTeleportAABB());
				List<Entity> a = new ArrayList();
				a.addAll(inPortal);
				for (Entity e : a) {
					if (!entsp.contains(e)) inPortal.remove(e);
				}
				if (ents.size() > 0) updatePylons();
				for (Entity e : ents) {
					if (inPortal.contains(e)) continue;
					double x = (e.posX
							- pos.getX())
							+ boundTo.getX(),
							y = (e.posY - pos.getY()) + boundTo.getY(),
							z = (e.posZ - pos.getZ()) + boundTo.getZ();
					AxisAlignedBB aabb = e.getEntityBoundingBox();
					int charge = (int) (((aabb.maxX - aabb.minX) * BTConfig.portalEntityBBBCost) + ((aabb.maxZ - aabb.minZ) * BTConfig.portalEntityBBBCost) + ((aabb.maxY - aabb.minY) * BTConfig.portalEntityBBBCost) + (RandUtil.getDistance(pos, boundTo) * BTConfig.portalPerBlockCost));
					System.out.println("chg " + charge + " dst " + RandUtil.getDistance(pos, boundTo));
					if (getUseableMana() >= charge) {
						useMana(charge);
						e.setPositionAndUpdate(x, y, z);
						inPortal.add(e);
						getBound().inPortal.add(e);
					}
				}
			}
		}
	}
	public TilePortalCore getBound() {
		if (boundTo == null) return null;
		return (TilePortalCore) world.getTileEntity(boundTo);
	}
	@Override
	public AxisAlignedBB getRenderBoundingBox() {
		return super.getRenderBoundingBox().grow(4);
	}
	public AxisAlignedBB getPortalAABB() {
		AxisAlignedBB aabb = new AxisAlignedBB(-1.5, 1, 0, 2.5, 4, 1);
		if(state == AlfPortalState.ON_X)
			aabb = new AxisAlignedBB(0, 1, -1.5, 1, 4, 2.5);

		return aabb;
	}
	public AxisAlignedBB getTeleportAABB() {
		AxisAlignedBB aabb = new AxisAlignedBB(pos.add(-1, 1, 0), pos.add(2, 4, 1));
		if(state == AlfPortalState.ON_X)
			aabb = new AxisAlignedBB(pos.add(0, 1, -1), pos.add(1, 4, 2));

		return aabb;
	}
	public AlfPortalState getStateByShape() {
		Map<EnumFacing, Schematic> m = shape.createRotations();
		Schematic shapeX = m.get(EnumFacing.SOUTH);
		shapeX.modToPos(pos);
		Schematic shapeZ = m.get(EnumFacing.EAST);
		shapeZ.modToPos(pos);
		int states = 0;
		for (StatePos s : shapeX.states) {
			if (s.state.equals(world.getBlockState(s.pos))) states++;
			else if(s.state.getBlock() == BTMod.dreamyPortal) states++;
		}
		if (states == shapeX.states.size()) return AlfPortalState.ON_X;
		states = 0;
		for (StatePos s : shapeZ.states) {
			if (s.state == world.getBlockState(s.pos)) states++;
			else if(s.state.getBlock() == BTMod.dreamyPortal) states++;
		}
		if (states == shapeZ.states.size()) return AlfPortalState.ON_Z;
		return AlfPortalState.OFF;
	}
	public boolean onWanded(boolean sneaking) {
		boolean bound = world.getBlockState(getPos()).getValue(BlockPortalCore.BOUND);
		if(bound && state == AlfPortalState.OFF && !sneaking) {
			chunkload(true);
						updatePylons();
						if (getUseableMana() < BTConfig.portalInitCost) {
							blockParticle();
							return true;
						}
					state = getStateByShape();
					getBound().state = getBound().getStateByShape();
					return true;
		} else if(bound && state == AlfPortalState.OFF && sneaking) {
			severConnection();
			return true;
		} else if(bound && (state == AlfPortalState.ON_X || state == AlfPortalState.ON_Z) && sneaking) {
			depower = true;
			return true;
		}
		return false;
	}
	
	private void blockParticle() {
		Botania.proxy.wispFX(pos.getX(), pos.getY(), pos.getZ(), 200, 200, 200, 1 + new Random().nextInt(3), 0, 0.5F, 0);
	}
	public void renderHUD(Minecraft mc, ScaledResolution res, World world, BlockPos pos) {
		int color = new Color(90, 205, 116).getRGB();
		String text = I18n.format(BTMod.dreamyPortal.getUnlocalizedName() + ".name");
		int x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		int y = res.getScaledHeight() / 2;
		x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		y -= 1;
		mc.fontRenderer.drawString(text, x, y, color);
		color = Color.BLUE.getRGB();
		text = I18n.format(BTMod.MODID + ".text.unbound");
		if (boundTo != null) {
			text = I18n.format(BTMod.MODID + ".text.bound");
			text += " X:" + boundTo.getX();
			text += " Y:" + boundTo.getY();
			text += " Z:" + boundTo.getZ();
		}
		y += 20;
		x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		y -= 1;
		mc.fontRenderer.drawString(text, x, y, color);
		color = Color.GREEN.getRGB();
		if (state == AlfPortalState.OFF) {
			HUDHandler.renderManaBar(x, y + 20, color, 1F, getUseableMana(), BTConfig.portalInitCost);
		}
	}
	@Override
	public BlockPos getBinding() {
		return boundTo;
	}
	@Override
	public boolean canSelect(EntityPlayer player, ItemStack wand, BlockPos pos, EnumFacing side) {
		return player.getEntityWorld().getBlockState(pos) == BTMod.dreamyPortal.getDefaultState() && ((TilePortalCore)world.getTileEntity(pos)).getStateByShape() != AlfPortalState.OFF;
	}
	@Override
	public boolean bindTo(EntityPlayer player, ItemStack wand, BlockPos pos, EnumFacing side) {
		if (canSelect(player, wand, pos, side)) {
			boundTo = pos;
			chunkload(true);
			getBound().chunkload(true);
			setState(true, false);
			NBTTagCompound nbt = world.getTileEntity(this.boundTo).writeToNBT(new NBTTagCompound());
			getBound().setState(boundTo != null, false);
			getBound().boundTo = this.pos;
			markDirty();
			getBound().markDirty();
			chunkload(false);
			getBound().chunkload(false);
			return true;
		}
		return false;
	}
	
	public void chunkload(boolean load) {
		//if (!world.isRemote && chunkloadTicket != null) {
		//	if (load) {
		//		ForgeChunkManager.forceChunk(chunkloadTicket, new ChunkPos(pos));
		//	}
		//	else ForgeChunkManager.unforceChunk(chunkloadTicket, new ChunkPos(pos));
		//}
	}
	
	@Nonnull
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
		super.writeToNBT(nbt);
		if (boundTo != null) {
			nbt.setInteger("bindX", boundTo.getX());
			nbt.setInteger("bindY", boundTo.getY());
			nbt.setInteger("bindZ", boundTo.getZ());
			nbt.setBoolean("bound", true);
		}
		
		nbt.setInteger("state", state.ordinal());
		nbt.setInteger("time", ticksOpen);
		nbt.setBoolean("depower", depower);
		return nbt;
	}
	
	@Nonnull
	public void readFromNBTB(NBTTagCompound nbt) {
		if (nbt.getBoolean("bound")) boundTo = new BlockPos(nbt.getInteger("bindX"), nbt.getInteger("bindY"), nbt.getInteger("bindZ"));
		state = AlfPortalState.values()[nbt.getInteger("state")];
		ticksOpen = nbt.getInteger("time");
		depower = nbt.getBoolean("depower");
	}
	@Nonnull
	@Override
	public void readFromNBT(NBTTagCompound nbt) {
		super.readFromNBT(nbt);
		readFromNBTB(nbt);
		
	}
	public void breakBlock() {
		if (pylon_act != TileCrystalPylon.EnumActivation.OFF) {
			pylon_act = TileCrystalPylon.EnumActivation.OFF;
			updatePylons();
		}
		chunkload(false);
		
		if (getBound() == null) return;
		getBound().chunkload(false);
		if (world.getBlockState(boundTo).getBlock() == BTMod.dreamyPortal) {
			setState(false, false);
		}
	}
	
	public void severConnection() {
		setState(false, false);
		updatePylons();
		boundTo = null;
		if (getBound() == null) return;
		getBound().chunkload(false);
		if (world.getBlockState(boundTo).getBlock() == BTMod.dreamyPortal) {
			setState(false, false);
			getBound().updatePylons();
		}
	}
	
	public void setState(boolean bound, boolean on) {
		world.setBlockState(pos, BTMod.dreamyPortal.getDefaultState()
				.withProperty(BlockPortalCore.BOUND, bound)
				.withProperty(BlockPortalCore.ON, on));
		((TilePortalCore) world.getTileEntity(pos)).readFromNBTB(this.writeToNBT(new NBTTagCompound()));
	}
	
	public void updateState() {
		if (world.getBlockState(pos).getValue(BlockPortalCore.BOUND) != (getBound() != null) ||
			world.getBlockState(pos).getValue(BlockPortalCore.ON) != (state != AlfPortalState.OFF))
			setState(getBound() != null, state != AlfPortalState.OFF);
		else if (getBound() != null && getBound().state != state) {
			state = getBound().state;
			updateState();
		} else if (getBound() != null && getBound().getBound() == null) {
			boundTo = null;
			updateState();
		}
	}
	
	
	@Override
	public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
		super.onDataPacket(net, packet);
		readFromNBT(packet.getNbtCompound());
		updatePylons();
	}
}

 

What I think is happening is, mana is handled on the server(I think) so there will never be any on the client, right?

Do I need to notify every client when a portal activates/deactivates?

What do I have to do?

 

If you can tell me Thanks! :D

Posted (edited)
12 minutes ago, GiantNuker said:

Do I need to notify every client when a portal activates/deactivates?

Yes, you should notify it every time something client-related changes.

Call World::notifyBlockUpdate with the current blockstate for both old and new for that.

Edited by Abastro

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted (edited)
6 minutes ago, Abastro said:

Yes, you should notify it every time something client-related changes.

Call World::notifyBlockUpdate with the current blockstate for both old and new for that.

Thanks, I thought I had to send a packet to every client player :) 

EDIT: Trying to update the TE, not the block.

Edited by GiantNuker
Posted

I'm not sure about the intricacies of botania, but if you want to update other client-rendering things like having particles on tile entities usually you need a packet. 

 

You want to write two messages. 

 

1. A message notifying the players in the area that the portal is active. (Which will then client-side show the particles.)

2. A message notifying the server that the player wants to recieve an update on whether the portal is active or not.

 

then in the custom TileEntity class you do something like.

 

    @Override
    public void onLoad() {
        if (worldObj.isRemote) {
            Your update message
        }
    }

to tell the client you want the portal active. 

 

When your block activates you want to make a sendToAllAround message that tells people around it that the portal is active. 

 

If you'd add that then players who walk from afar and load your TE will know the portal is active, and players who are near when it activates will know it's active. You don't have to send a packet with every particle, just tell the client it's active and make it use particles from there. 

Posted
9 minutes ago, oldcheese said:

I'm not sure about the intricacies of botania, but if you want to update other client-rendering things like having particles on tile entities usually you need a packet. 

 

You want to write two messages. 

 

1. A message notifying the players in the area that the portal is active. (Which will then client-side show the particles.)

2. A message notifying the server that the player wants to recieve an update on whether the portal is active or not.

 

then in the custom TileEntity class you do something like.

 


    @Override
    public void onLoad() {
        if (worldObj.isRemote) {
            Your update message
        }
    }

to tell the client you want the portal active. 

 

When your block activates you want to make a sendToAllAround message that tells people around it that the portal is active. 

 

If you'd add that then players who walk from afar and load your TE will know the portal is active, and players who are near when it activates will know it's active. You don't have to send a packet with every particle, just tell the client it's active and make it use particles from there. 

I want to send it when the state updates.

Posted

Christ. This isn't that complicated folks.

 

Step 1: Override these methods

Step 2: Call these methods whenever the data changes and the client needs to know about it

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

AFAIK notifyBlockUpdate is sufficient.

It works both on TEs and Blocks, GiantNuker.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

  • 8 months later...
Posted
On 9/22/2017 at 9:15 PM, Draco18s said:

Christ. This isn't that complicated folks.

 

Step 1: Override these methods

Step 2: Call these methods whenever the data changes and the client needs to know about it

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

Posted
25 minutes ago, Ice2670 said:

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

Don't bump an over-half-year-old thread. Just make your own issue thread with what you've tried.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted
2 minutes ago, Abastro said:

Don't bump an over-half-year-old thread. Just make your own issue thread with what you've tried.

^^^ Very good advice, please never comment on existing threads with a new issue.

 

33 minutes ago, Ice2670 said:

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

@Ice2670 Since you haven't made a new thread yet, and this is a common issue, I'll show how I do it. This is my personal preference, and it works well for me, feel free to adapt it. My personal preference is to have a superclass that handles all my syncing & capability stuff and have all my TileEntities extend it. My class is called TileEntityBase and you can view it here. It is adapted from canitzp's mod MetalWorks.

The actual Syncing packets are registered here, and the class is here.

To get my energy capability I simply Override getEnergy() in my superclass.

You can see an examples of how I use TileEntityBase here, here and here.

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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