Jump to content

Getting EntityPlayer parameter outside of the method itself


Recommended Posts

Posted

Hey guys,

 

probably a simple question but I can't figure it out.

 

I need to get the player in order to do a few things (consume their held item and read from NBT to name two), but just adding EntityPlayer player to my method obviously breaks stuff*. So, is there any other clever way I can get player information where I usually couldn't?

 

[spoiler=*]

By break stuff, I mean:

    public void actionPerformed(GuiButton guibuttonr) {
    	switch(guibutton.id) {
    	case 1:
    		System.out.println("You pressed 7!");
    		break;

This works...

 

    public void actionPerformed(GuiButton guibutton, EntityPlayer player) {
    	switch(guibutton.id) {
    	case 1:
    		System.out.println("You pressed 7!");
    		break;

This does not work.

 

width=463 height=200

http://s13.postimg.org/z9mlly2av/siglogo.png[/img]

My mods (Links coming soon)

Cities | Roads | Remula | SilvaniaMod | MoreStats

Posted

You can use 'FMLClientHandler.instance().getClient().thePlayer;' to get an EntityPlayerMP instance of the player using the Gui, but remember that Gui and EntityPlayerMP are all client-side. Anything you do to the player here will not be stored on the server.

 

Your best bet would be to use the above to get the player in order to send a packet to that player on the server, then do whatever you need to do there. Your PacketHandler class should already have the player object available for you.

Posted

Alright, so in order to read/edit NBT and inventory, I'll need a packet?

Time to learn how to use packets! I assume the wiki tutorial isn't totally out of date..? I've been putting packets off for a long time on my "to learn" list, so I really do need to get around to it.

 

Packets are really easy when it comes down to it.

 

On the client sided function, you add this:

 

ByteArrayOutputStream bt = new ByteArrayOutputStream();
	DataOutputStream out = new DataOutputStream(bt);
	try
	{
		//we will first need to know what action we're performing when the packet is read.
		//A switch statement on the first integer will let us do that
		out.writeInt(1);

		//Then the data relevant to the action being performed.  In my case, I'm increasing the player's
		//health by 1, so I'm sending the value I want to set it to.
		//(Probably should calculate this server side....)
		out.writeFloat(par3EntityPlayer.getHealth()+1);

		//Then we construct a packet.  The string parameter here is the "channel" we're using.  Usually mod_id
		Packet250CustomPayload packet = new Packet250CustomPayload("Artifacts", bt.toByteArray());

		//What player to send it to, not used here, but in server->client communication you'd need it
		Player player = (Player)par3EntityPlayer;

		//And send it off!
		PacketDispatcher.sendPacketToServer(packet);
		par1ItemStack.damageItem(1, par3EntityPlayer);
	}
	catch (IOException ex)
	{
		System.out.println("couldnt send packet!");
	}

 

Before we can do anything with that though, we need to set up our mod to be a NetworkMod.

 

@NetworkMod(clientSideRequired = true, serverSideRequired = false,
clientPacketHandlerSpec = @SidedPacketHandler(channels = {"Artifacts"}, packetHandler = PacketHandlerClient.class),
serverPacketHandlerSpec = @SidedPacketHandler(channels = {"Artifacts"}, packetHandler = PacketHandlerServer.class))

 

Here you can see the channel being declared (there's a character limit, I think it's 16) and that we're setting up two classes to handle packets, one client-side, one server-side.  You can use the same class for both, but it's not good practice in the long term.

 

Finally, the packet handler class

 

public class PacketHandlerServer implements IPacketHandler{
    @Override
    public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
    {
        //again we need to check for the proper channel
        if (packet.channel.equals("Artifacts"))
        {
            handleRandom(packet, player);
        }
    }

    private void handleRandom(Packet250CustomPayload packet, Player player)
    {
        EntityPlayer p = (EntityPlayer) player;
        World world = p.worldObj;
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.data));
        //System.out.println("Packet get");
        try
        {
            //here's that first integer again.
            int effectID = dis.readInt();
            switch(effectID) {
            	case 1:
                        //and then the data we sent
            		p.setHealth(dis.readFloat());
            		break;
            }
        }
        catch  (IOException e)
        {
            System.out.println("Failed to read packet");
        }
        finally
        {
        }
    }
}

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

Alright, looks relatively simple. Where does that first code-snippet go though - in the GUI class or the client-side packet handler (nothing else in there?)

 

Is there supposed to be a method going with that snippet too by the way? Where's it getting the parameters from?

 

Finally, is there any way to streamline packets? Right now I'll be having probably 8 buttons (maybe 18, depending how I handle it and what works) which would need to be sent.

 

 

Thanks for the help :)

width=463 height=200

http://s13.postimg.org/z9mlly2av/siglogo.png[/img]

My mods (Links coming soon)

Cities | Roads | Remula | SilvaniaMod | MoreStats

Posted

Alright, looks relatively simple. Where does that first code-snippet go though - in the GUI class or the client-side packet handler (nothing else in there?)

 

The first chunk would go in your GUI class.  The place where the action is being performed.  In my case, it was in the item class's onRightClick / itemInteractionForEntity / hitEntity function(s).  Wherever it is that you need to go "world needs to change here" but you don't have the server's world (or access to any world, even!  Packets can be fired off from anywhere in the program's operation, and when handled by the server's packet handler, you will have access to the player that the packet came from as well as the world).

 

Is there supposed to be a method going with that snippet too by the way? Where's it getting the parameters from?

 

Yeah, I stripped it out as its not important what function it's from.  I pulled it from:

public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World,	EntityPlayer par3EntityPlayer) {

But the only reason I use the par3EntityPlayer is because I am operating on that entity.  But now that I've changed it to not send the health total (just a "1" so that on the packet handler side I get what the server believes is the player's health and adds 1, to avoid race conditions) I could strip that out, even.

 

Finally, is there any way to streamline packets? Right now I'll be having probably 8 buttons (maybe 18, depending how I handle it and what works) which would need to be sent.

 

How do you mean?

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

Alright, I think I get it. From the looks of it, I need to be sending packets from my block class for things like checking the players NBT, because my GUI class has no method of doing it as it's client side. I could send the packet at the time the player right-clicks the block, as I know 100% the NBT value wont change after that moment until I've used it, and I can store it as a variable in the GUI for later use... is that good or bad? :P

 

As for streamlining, do I need the entire snippet of code for each and every event which sends a packet, or would there be a smaller way of doing it? IE, do I need to have that entire snippet repeated for each button, or can I be clever with variables or something?

width=463 height=200

http://s13.postimg.org/z9mlly2av/siglogo.png[/img]

My mods (Links coming soon)

Cities | Roads | Remula | SilvaniaMod | MoreStats

Posted

Alright, I think I get it. From the looks of it, I need to be sending packets from my block class for things like checking the players NBT, because my GUI class has no method of doing it as it's client side. I could send the packet at the time the player right-clicks the block, as I know 100% the NBT value wont change after that moment until I've used it, and I can store it as a variable in the GUI for later use... is that good or bad? :P

 

Not sure, try it and find out!

 

Experimentation is why I like modding so much. ^..~

 

As for streamlining, do I need the entire snippet of code for each and every event which sends a packet, or would there be a smaller way of doing it? IE, do I need to have that entire snippet repeated for each button, or can I be clever with variables or something?

 

The first chunk needs to go everywhere you need to send a packet.  You might be able to get away with creating a utils class/function that could handle it, so you'd just be passing the required info to the utils class/function.  It'd be a little less flexible, though, as you wouldn't be able to handle complex information (i.e. if one button sends two ints and a float, the second button sends four ints and a string, the third button passes three floats, etc.).

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

I was experimenting while I waited for a reply. Seems to work as far as ints go, but I couldn't get it to work for a double - it throws the error in the packet handler. I'm sure I can figure that out with some experimenting.

 

So, hopefully the last question. Currently, I've got the packet to send an integer of 4 to my client from the server. How can I then go and read that 4 in the GUI? I want to print it as text on the GUI, so I need to convert it from an int (or double) to a string too

width=463 height=200

http://s13.postimg.org/z9mlly2av/siglogo.png[/img]

My mods (Links coming soon)

Cities | Roads | Remula | SilvaniaMod | MoreStats

Posted
So, hopefully the last question. Currently, I've got the packet to send an integer of 4 to my client from the server. How can I then go and read that 4 in the GUI? I want to print it as text on the GUI, so I need to convert it from an int (or double) to a string too

 

String str = "" + myInt;

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

Yeah, I can get that in the ClientPacketHandler class but I need to pass it to other classes to use.

Is there an "onPacketRecieved" method or something? I want to run some code when certain packets are received.

 

You mean this? :P

public class PacketHandlerServer implements IPacketHandler{
    @Override
    public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)

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.

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

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