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



×
×
  • Create New...

Important Information

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