Jump to content

Recommended Posts

Posted (edited)

I have a block that when right-clicked will open a GUI, but only if the player has some requirements. I've managed how to check this requirements using the PlayerInteractEvent (since all the stuff i have to control is stored server side but the gui is client side so that checks will fail), but if it turns that the player can't open the gui i get a chat message that warn the player but the gui still opens. Here is a picture of what i mean
wzLqEak.png
In this case the player was not allowed to open the GUI, infact there is a chat message that says that. But the GUI is opened too. So how can i prevent the GUI to open? This is my block code

 
	package com.cf.blocks;
	import java.util.Random;
	import javax.annotation.Nullable;
	import com.cf.CoreFaction;
import com.cf.entities.TileEntityBuyer;
import com.cf.entities.TileEntityCore;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.proxy.GuiHandler;
import com.cf.utils.TerritoryUtils;
import com.cf.utils.Utils;
	import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
	public class BlockCore extends BlockContainer {
	    public BlockCore() {
        super(Material.IRON);
        this.setCreativeTab(CreativeTabs.MISC);
        this.setHardness(100.0F);
        this.setResistance(2000.0F);
    }
	    public EnumBlockRenderType getRenderType(IBlockState state) {
        return EnumBlockRenderType.MODEL;
    }
	    @SideOnly(Side.CLIENT)
    public BlockRenderLayer getBlockLayer() {
        return BlockRenderLayer.CUTOUT_MIPPED;
    }
	    public boolean isOpaqueCube(IBlockState state) {
        return false;
    }
	    public boolean isFullCube(IBlockState state) {
        return false;
    }
	    @Override
    public EnumPushReaction getMobilityFlag(IBlockState state) {
        return EnumPushReaction.BLOCK;
    }
	    @SideOnly(Side.CLIENT)
    public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {
        for (int i = 0; i < 1; ++i) {
            int j = rand.nextInt(2) * 2 - 1;
            int k = rand.nextInt(2) * 2 - 1;
            double d0 = (double) pos.getX() + 0.5D + 0.25D * (double) j;
            double d1 = (double) ((float) pos.getY() + rand.nextFloat());
            double d2 = (double) pos.getZ() + 0.5D + 0.25D * (double) k;
	            worldIn.spawnParticle(EnumParticleTypes.END_ROD, d0, d1, d2, rand.nextGaussian() * 0.003D,
                    rand.nextGaussian() * 0.003D, rand.nextGaussian() * 0.003D, new int[0]);
        }
    }
	    /**
     * Returns the quantity of items to drop on block destruction.
     */
    public int quantityDropped(Random random) {
        return 0;
    }
	    /**
     * Get the Item that this Block should drop when harvested.
     */
    @Nullable
    public Item getItemDropped(IBlockState state, Random rand, int fortune) {
        return null;
    }
	    @Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
            EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
        if(worldIn.isRemote)
            playerIn.openGui(CoreFaction.INSTANCE, GuiHandler.CORE_GUI_ID, worldIn, pos.getX(), pos.getY(), pos.getZ());
        return worldIn.isRemote;
    }
	    @Override
    public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn) {
        // TODO
        super.onBlockDestroyedByExplosion(worldIn, pos, explosionIn);
    }
	    @Override
    public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, IBlockState state) {
        // TODO
        super.onBlockDestroyedByPlayer(worldIn, pos, state);
    }
	    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta) {
        return new TileEntityCore();
    }
	    @Override
    public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
        if (!worldIn.isRemote) {
            TileEntity te = worldIn.getTileEntity(pos);
            if (te != null && te instanceof TileEntityCore) {
                Territory t = TerritoryUtils.getTerritoryByPos(pos, worldIn.provider.getDimension());
                if (t != null) {
                    Faction f = TerritoryUtils.getFaction(t);
                    if (f != null) {
                        ((TileEntityCore) te).setName(f.getName());
                        ((TileEntityCore) te).setOpen(false);
                    }
                }
            }
        }
    }
}



This is the PlayerInteractEvent

 
	package com.cf.events;
	import com.cf.blocks.BlockCore;
import com.cf.core.CFBlocks;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.utils.FactionUtils;
import com.cf.utils.TerritoryUtils;
import com.cf.utils.Utils;
	import net.minecraft.block.Block;
import net.minecraft.block.BlockBrewingStand;
import net.minecraft.block.BlockButton;
import net.minecraft.block.BlockChest;
import net.minecraft.block.BlockDispenser;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockDropper;
import net.minecraft.block.BlockFenceGate;
import net.minecraft.block.BlockFurnace;
import net.minecraft.block.BlockHopper;
import net.minecraft.block.BlockLever;
import net.minecraft.block.BlockNote;
import net.minecraft.block.BlockRedstoneComparator;
import net.minecraft.block.BlockRedstoneRepeater;
import net.minecraft.block.BlockTrapDoor;
import net.minecraft.init.Blocks;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
	public class EventBlockInteract {
    @SubscribeEvent
    public void onInteract(PlayerInteractEvent.RightClickBlock event) {
        Territory t = TerritoryUtils.getTerritoryByPos(event.getPos(), event.getEntityPlayer().dimension);
        if (t != null) {
            Faction f = TerritoryUtils.getFaction(t);
            if (event.getWorld().getBlockState(event.getPos()).getBlock() == CFBlocks.core) {
                if (f == null)
                    event.setCanceled(true);
                else if (f.getMembers().contains(event.getEntityPlayer().getUniqueID())) {
                    if(!f.getOwner().equals(event.getEntityPlayer().getUniqueID())) {
                        event.setCanceled(true);
                        Utils.sendMessage(event.getEntityPlayer(),
                                Utils.getTranslation("block.core.nopermission", TextFormatting.RED));
                    }
                } else {
                    event.setCanceled(true);
                    Utils.sendMessage(event.getEntityPlayer(),
                            Utils.getTranslation("block.core.fail", TextFormatting.RED)); //THIS IS THE CHAT MESSAGE THAT APPEARS IN THE IMAGE
                }
            }
        }
    }
}


This is my GuiHandler

 
	package com.cf.proxy;
	import com.cf.entities.TileEntityCore;
import com.cf.gui.GuiCore;
	import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
	public class GuiHandler implements IGuiHandler {
	    public static int CORE_GUI_ID = 0;
    
    @Override
    public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
        return null;
    }
	    @Override
    public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
        if(ID == CORE_GUI_ID) {
            BlockPos pos = new BlockPos(x, y, z);
            TileEntity tileEntity = world.getTileEntity(pos);
            if(tileEntity instanceof TileEntityCore) {
                return new GuiCore((TileEntityCore)tileEntity);
            }
        }
        return null;
    }
}


and this is how i register it in the ClientProxy 

public void init() {
        NetworkRegistry.INSTANCE.registerGuiHandler(CoreFaction.INSTANCE, new GuiHandler());
    }
Edited by JimiIT92

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

You need to have something like this:

1. On block activation the client sends a packet to the server.

2. The server checks what it needs to check, and sends a reply packet with the results.

3. The client receives the packet and either opens the gui, or tells the player that the permission was denied.

Posted

That what was i thought on first but if possibile i want to avoid handling packets. But i guess is the only possible solution :/

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted (edited)

Why don't you just do

if(!world.isRemote){
	playerIn.displayGui(new YourGui);
}

that will also work if you move your registration of the guiHandler to your common registration. You will have access to all server variable as well, no need for packets. The best answer is usually the simplest, don't make more out of this than it is.

Edited by draganz
Posted
2 minutes ago, draganz said:

Why don't you just do


if(!world.isRemote){
	playerIn.displayGui(new YourGui);
}

that will also work if you move your registration of the guiHandler to your common registration. You will have access to all server variable as well, no need for packets. 

Good job not reading the thread. He can't do this client-side-only because he needs to know if the user is ALLOWED TO OPEN IT which is information only the server has.

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
2 minutes ago, Draco18s said:

Good job not reading the thread. He can't do this client-side-only because he needs to know if the user is ALLOWED TO OPEN IT which is information only the server has.

I can't also do that call because i'll need to implement IInteractionObject into my GUI, wich is not what i want since is just a simple GUI with no inventory or container

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

You don't need to use an event to control the behaviour of a class which you wrote yourself. You can just do the checking in the onBlockActivated method itself, all in one place.

Posted (edited)

OOO, I see, typo on my part, sorry, don't do player.displayGui, do player.openGui, still do the check of !world.isRemote, though. Just make sure your guihandler has been registered via the common (both server and client). Sorry about that, slight typo.

 

Edited by draganz
Posted

So i should just send a message (via SimpleNetworkWrapper) to the client with all the necessary informations (taken from the server) and inside the message decide if open the Gui or not?

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

Ok, so i send a message from the onBlockActivated method to the server, but server crash with this error

[00:10:31] [Server thread/ERROR] [FML]: FMLIndexedMessageCodec exception caught
java.lang.RuntimeException: Missing
    at net.minecraftforge.fml.server.FMLServerHandler.getClientToServerNetworkManager(FMLServerHandler.java:281) ~[FMLServerHandler.class:?]
    at net.minecraftforge.fml.common.FMLCommonHandler.getClientToServerNetworkManager(FMLCommonHandler.java:545) ~[FMLCommonHandler.class:?]
    at net.minecraftforge.fml.common.network.FMLOutboundHandler$OutboundTarget$8.selectNetworks(FMLOutboundHandler.java:245) ~[FMLOutboundHandler$OutboundTarget$8.class:?]
    at net.minecraftforge.fml.common.network.FMLOutboundHandler.write(FMLOutboundHandler.java:293) ~[FMLOutboundHandler.class:?]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:651) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:112) ~[MessageToMessageEncoder.class:4.0.23.Final]
    at io.netty.handler.codec.MessageToMessageCodec.write(MessageToMessageCodec.java:116) ~[MessageToMessageCodec.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:706) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:741) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.DefaultChannelPipeline.writeAndFlush(DefaultChannelPipeline.java:895) ~[DefaultChannelPipeline.class:4.0.23.Final]
    at io.netty.channel.AbstractChannel.writeAndFlush(AbstractChannel.java:240) ~[AbstractChannel.class:4.0.23.Final]
    at net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper.sendToServer(SimpleNetworkWrapper.java:294) [SimpleNetworkWrapper.class:?]
    at com.cf.blocks.BlockCore.onBlockActivated(BlockCore.java:105) [BlockCore.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.processRightClickBlock(PlayerInteractionManager.java:477) [PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processRightClickBlock(NetHandlerPlayServer.java:706) [NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:68) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:13) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:21) [PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_131]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_131]
    at net.minecraft.util.Util.runTask(Util.java:28) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:743) [MinecraftServer.class:?]
    at net.minecraft.server.dedicated.DedicatedServer.updateTimeLightAndEntities(DedicatedServer.java:408) [DedicatedServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:688) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:537) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_131]



This is the message class

 
	package com.cf.network;
	import com.cf.CoreFaction;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.utils.TerritoryUtils;
	import io.netty.buffer.ByteBuf;
import net.minecraft.util.IThreadListener;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
	public class GuiCoreServerMessage implements IMessage{
	    private String name;
	    public GuiCoreServerMessage() {
        
    }
    
    public GuiCoreServerMessage(String n) {
        this.name = n;
    }
    
    @Override
    public void fromBytes(ByteBuf buf) {
        this.name = ByteBufUtils.readUTF8String(buf);
    }
	    @Override
    public void toBytes(ByteBuf buf) {
        ByteBufUtils.writeUTF8String(buf, name);
    }
    
    public static class Handler implements IMessageHandler<GuiCoreServerMessage, IMessage> {
        @Override
        public IMessage onMessage(final GuiCoreServerMessage message, final MessageContext ctx) {
            IThreadListener mainThread = CoreFaction.PROXY.getListener(ctx);
            mainThread.addScheduledTask(new Runnable() {
                @Override
                public void run() {
                    Territory t = TerritoryUtils.getTerritoryByName(message.name);
                    if(t != null) {
                        Faction f = TerritoryUtils.getFaction(t);
                        if(f != null)
                            System.out.println(f.getName());
                    }
                    
                }
            });
            return null;
        }
        
    }
}



This is how i register the message and the channel

public static SimpleNetworkWrapper NETWORK;
    
    @EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);
        NETWORK.registerMessage(GuiCoreServerMessage.Handler.class, GuiCoreServerMessage.class, 0, Side.SERVER);
}



and this is how i send the message from the block

@Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
            EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
        if(!worldIn.isRemote) {
            TileEntity te = worldIn.getTileEntity(pos);
            if(te instanceof TileEntityCore) {
                CoreFaction.NETWORK.sendToServer(new GuiCoreServerMessage(((TileEntityCore)te).getName()));
            }
        }
        return true;
    }



What am i missing? :/

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted (edited)

Woops, my bad xD Changed that and now it sends the message, hope everything works as intended now :)
EDIT: Yes, it works now, thanks everybody for your help :)

Edited by JimiIT92

Don't blame me if i always ask for your help. I just want to learn to be better :)

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.