Jump to content

Recommended Posts

Posted

Heyho guys!

 

I created an Entity which adjusts its position to its owner's position (normally the player). Now I encountered a small problem:

The Entity's y position is not updated correctly. I have one line of code which is called in onUpdate on server side to update the entities position:

this.setPositionAndRotation(this.owner.posX, this.owner.posY + 10.0F, this.owner.posZ, this.owner.rotationYaw, this.owner.rotationPitch);

 

On the server, the Entity is at the right position ten blocks above the player but on the client, the entity is just at the player's origin point.

The problem is that basically everything works, if the player moves, the entity moves too. I tried to set the height of the entity to a constant value like this:

this.setPositionAndRotation(this.owner.posX, 70.0F, this.owner.posZ, this.owner.rotationYaw, this.owner.rotationPitch);

On the server side, the entity is at this position but on the client side its rendered at the height I spawned it, no matter if this was 70 or maybe 90.

 

I'll post some code here, but I'm really not sure which code you'll need so please write if you need more.

 

Entity Base class:

package com.bedrockminer.magicum.entity.magic;

import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;

import com.bedrockminer.magicum.damage.DamageSourceMagic;
import com.bedrockminer.magicum.element.Elements;
import com.bedrockminer.magicum.util.elements.ElementMagicHelper;

import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;

public abstract class EntityMagic extends Entity implements IEntityAdditionalSpawnData {

protected EntityLivingBase owner;
protected boolean isInGround;
protected int tileX;
protected int tileY;
protected int tileZ;

public EntityMagic(World par1World) {
	super(par1World);
	this.setSize(1.0F, 1.0F);
}

public EntityMagic(World par1World, EntityLivingBase owner) {
	this(par1World);
	this.owner = owner;
}

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

public void onCollideWithEntity(Entity e) {
	this.performMagicEffect(e);
}

@Override
public void onUpdate() {
	super.onUpdate();
	if (!this.worldObj.isRemote && (this.elements == null || this.mainElement == null)) {
		this.setDead(); //Kill the entity if it has no data. This is only for startup, it happens never in normal gameplay
		return;
	}

	if (!this.worldObj.isRemote && !this.isDead) {
		this.checkForBlockCollisions();
		this.checkForEntityCollisions();
	}
}

protected void checkForBlockCollisions() {
	this.isInGround = false;
	Block block = this.worldObj.getBlock(this.tileX = (int) this.posX, this.tileY = (int) this.posY, this.tileZ = (int) this.posZ);
        if (block.getMaterial() != Material.air) {
            block.setBlockBoundsBasedOnState(this.worldObj, this.tileX, this.tileY, this.tileZ);
            AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, this.tileX, this.tileY, this.tileZ);
            if (axisalignedbb != null && axisalignedbb.intersectsWith(this.boundingBox)) {
            	this.isInGround = true;
            	this.onCollideWithBlock(this.worldObj, this.tileX, this.tileY, this.tileZ);
            }
        }
}

protected void checkForEntityCollisions() {
	List<?> entities = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox, new EntitySelector(this.owner));
	if (entities.size() > 0) {
		for (Object e : entities)
			this.onCollideWithEntity((Entity)e);
	}
}

@Override
protected void entityInit() {
}

@Override
protected void readEntityFromNBT(NBTTagCompound var1) {
}

@Override
protected void writeEntityToNBT(NBTTagCompound var1) {
}

private static class EntitySelector implements IEntitySelector {

	private EntityLivingBase owner;

	private EntitySelector (EntityLivingBase owner) {
		this.owner = owner;
	}

	@Override
	public boolean isEntityApplicable(Entity entity) {
		return !(entity instanceof EntityMagic || entity == this.owner);
	}
}
}

 

Special Entity Class:

package com.bedrockminer.magicum.entity.magic;

import io.netty.buffer.ByteBuf;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.world.World;

import com.bedrockminer.magicum.Main;
import com.bedrockminer.magicum.client.particle.ParticleEffect;
import com.bedrockminer.magicum.util.entity.PositionUtil;

public class EntityMagicBeam extends EntityMagic {

protected EntityMagicBeam childMagic;
protected EntityMagicBeam parentMagic;
protected int childCount = 1;
public boolean isMainMagic;

public EntityMagicBeam(World world) {
	super(world);
	this.width = 0.5F;
	this.height = 0.5F;
}

public EntityMagicBeam(World world, EntityLivingBase owner) {
	super(world, owner);
	this.width = 0.5F;
	this.height = 0.5F;
}

@Override
public void onUpdate() {
	super.onUpdate();
	if (!this.worldObj.isRemote) {
		if (!this.isMainMagic && this.parentMagic == null) { //Kills the Entity if it has no data
			this.setDead();
			return;
		}

		if (!this.isInGround && this.childCount < this.getMaxLength() && this.childMagic == null) { //To test the basic behaviour i disabled the children
			this.childMagic = new EntityMagicBeam(this.worldObj, this.getOwner());
			this.childMagic.childCount = this.childCount + 1;
			this.childMagic.parentMagic = this;
			this.updateChildPosition();
			this.worldObj.spawnEntityInWorld(this.childMagic);
		}

		if (this.isMainMagic && this.owner != null) { //On the server it does its work correctly!
			Main.log("Old Position:" + this.posX + "," + this.posY + "," + this.posZ);
			this.setPositionAndRotation(this.owner.posX, 70.0F, this.owner.posZ, this.owner.rotationYaw, this.owner.rotationPitch);
			Main.log("Called! new position:" + this.posX + "," + this.posY + "," + this.posZ);
		}

		if (this.childMagic != null) {
			this.updateChildPosition();
		}
	}

	if (this.worldObj.isRemote) {
		this.doParticleEffects();
	}
}

protected void doParticleEffects() { //Actually only a control for the entities position
	ParticleEffect.spawnElementParticle(Elements.Fire, this.posX, this.posY, this.posZ, 0, 0, 0);
}

@Override
public void setDead() {
	super.setDead();
	if (this.childMagic != null) //Used to clear the complete beam after an obstacle
		this.childMagic.setDead();
}

protected void updateChildPosition() {
	PositionUtil.adjustEntityPositionToOwnerRotation(this.childMagic, this, 1.0D, 0.0F);
}
}

 

The entity is spawned with this method on Server side:

this.controlledEntity = new EntityMagicBeam(this.world, this.source);
this.controlledEntity.isMainMagic = true;
this.controlledEntity.setPositionAndRotation(this.source.posX, this.source.posY, this.source.posZ, this.source.rotationYaw, this.source.rotationPitch);
//The Entity position is set to the owners position directly in Order to let it spawn in a loaded chunk. After this, the position is set via the onUpdate method.
this.source.worldObj.spawnEntityInWorld(this.controlledEntity);

 

Registration:

EntityRegistry.registerModEntity(EntityMagicBeam.class, "magic_beam", 0, Main.instance, 128, 1, true);

(I'm actually not quite sure if I registered the entity properly because I read some tutorials which were quite different)

 

 

I hope anybody understands what the problem is or give me at least a hint what may cause problems with this.

Thanks in advance!

Posted

Have you tried using the different ways of registering entities to see if it makes any difference? The way I register is lime so (semi-pseudo code):

int entityId = EntityRefistry.findSomethingOrOtherId();
EntityRegistry.registerGlobalEntityId(params);
EntityRegistry.registerMidEntity(params);

Wherever I am I am asked to use the id, I use that entityId (I have this in a creatEntity method, so entityId is changed for each entity).

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

I have created some other mods which just use registerModEntity and this worked but this were Entities which were not controlled by the player.

I think, the Entity itself works... (I think...)

 

EDIT:

Actually the same issue occurs if I change the registration... I have no idea what can cause this because its such a weird behaviour. I checked the posX...posZ vars of the Entity: They have the right values on server but wrong on client. Maybe a sync error? How could I fix this with Entities?

Posted

Is the actual collision box of the entity up in the air, or just the rendered model?  If you really want to visually check where the entity is on the client side you should press F3+B while playing the game -- this will show you the bounding box of the entity.  I recommend doing that with all custom entities.

 

Anyway, I'm suggesting that your entity might actually be in proper position but your model might be rendering in wrong position.  If that is the case, you'll see the bounding box isn't on the entity when you view it.  To fix that you'd have to check whether your model has correct rotation points, or you can also just translate the model during rendering.

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

Posted

Well, at this stage of Entity development I don't use a special renderer, so the Entity is actually a white box which is perfectly aligned with the bounding box.

 

I checked posX, posY and posZ and on client side they DO have wrong values.

I really can't understand this, because I searched for every access to methods or variables which change the position but there is nothing which can cause the error.

 

>:(

Posted

The built-in fields for entities should be automatically synced between client and server.  You only have to worry about syncing when you add custom fields. 

 

So assuming you're using built-in posX type fields, then they should be synced.  Note that perhaps you have a typo or perhaps you have accidently declared local variables that are actually being accessed.  In Eclipse you should hover over the posX variables and see what Eclipse says about where they are declared.  You want to confirm that they are the ones you inherited from the Entity class, not something you declared yourself.

 

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

Posted

Maybe this helps:

If I output the values every Tick I get this result:

[15:22:17] [server thread/INFO] [FML]: Position:(10.936262235862642|76.0|12.26463907810521)
[15:22:17] [Client thread/INFO] [FML]: Position:(10.90625|66.0|12.25)

The entity should be 10 blocks above the player who us standing at 10.9|66|12.3.

 

 

 

If I set the height to a constant value (80) and add this line to the client-side only code

this.posY = 80;

I see the Entity still at the player's position but it is placed at y=80 everytime a player moves; and afterwards (1 Tick later) it's set back to the players position.

 

 

This seems to be affected only by the setPosition method, all the other code is ok: I created a new Entity which only adjusts its position to the player's one (with an offset) and this shows the same behaviour.

package com.bedrockminer.magicum.entity.magic;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;

import com.bedrockminer.lib.util.render.Vertex;
import com.bedrockminer.magicum.Main;

public class EntityMagicTest extends Entity {

private EntityLivingBase owner;

public EntityMagicTest(World par1World) {
	super(par1World);
}

public EntityMagicTest(World par1World, EntityLivingBase owner) {
	super(par1World);
	this.owner = owner;
	this.copyLocationAndAnglesFrom(owner);
}

@Override
public void onUpdate() {
	super.onUpdate();
	if (!this.worldObj.isRemote && this.owner == null) {
		this.setDead();
		return;
	}
	if (!this.worldObj.isRemote) {
		this.setLocationAndAngles(this.owner.posX, this.owner.posY + 1, this.owner.posZ, 0, 0); //Or setPosition? I think they are similar to each other
		Main.log("OwnerY:" + this.owner.posY + ", thisY:" + this.posY);
	}
	Main.log("Position:" + new Vertex(this.posX,this.posY,this.posZ));
}

@Override
protected void entityInit() {
}

@Override
protected void readEntityFromNBT(NBTTagCompound var1) {
}

@Override
protected void writeEntityToNBT(NBTTagCompound var1) {
}

}

Posted

Sounds like the server is some how missing the fact it should be at the point you have said. Are you sure there are no syncing issues?

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

I experimented a bit and encountered the following:

 

-x, y and z value show this behaviour

-The position of the value is the position that was set before spawning the entity, as if the method there was called several times (its only called once, I checked it). If I set the before spawn method to (owner.posX + 5, ...) the Entity is always five blocks away from the owner, no matter how I try to replace it. But the method is in the constructor and only called once, I only use it to ensure the Entity doesn't spawn in an empty chunk!

-The values on client side are slightly different from the once on the server side. Is this normal? (0.0 on Server -> 0.34375 or -0.40625 on client)

Posted

I use something like:

 

if (!world.isRemote) {

sEntity = new EntityController(world);

sEntity.setPosition(x + 0.5, y + 1, z + 0.5);

float fYaw = DEBClasses_v1.fourRotations(entity.rotationYaw);

sEntity.rotationYaw = fYaw;

sEntity.sX = x;

sEntity.sY = y;

sEntity.sZ = z;

world.spawnEntityInWorld(sEntity);

}

 

might help, definitly works for me with setPosition

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.