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

    • I need to know what mod is doing this crash, i mean the mod xenon is doing the crash but i want to know who mod is incompatible with xenon, but please i need to know a solution if i need to replace xenon, i cant use optifine anymore and all the other mods i tried(sodium, lithium, vulkan, etc) doesn't work, it crash the game.
    • I have been trying to solve a consistent crashing issue on my brother's computer where it will crash during the "Scanning Mod Candidates" phase of the loading process that starts when you click the play button on the Minecraft launcher. The issue seems to stem from a missing library that it mentions in the log file I provide below. I might I'm missing the bigger issue here for a smaller one but hopefully someone can find what I'm missing. Here's all of the stuff that I've been able to figure out so far: 1. It has nothing to do with mods, the crash happened with a real modpack, and even when I made a custom modpack and launched it without putting ANY mods into it (That is where the log file comes from by the way). 2. I have tried to find this class like a file in the Minecraft folders, but I've had no luck finding it (I don't think it works like that, but since I really don't understand how it works, I just figured I'd try). 3. I haven't seen anyone else have this issue before. 4. I know that my modpack (with mods) does work since I've run it on my computer, and it works fantastic. For some reason my brother's computer can't seem to run anything through curseforge. 5. This is for Minecraft version 1.20.1, Minecraft launcher version 3.4.50-2.1.3, forge 47.3.0, and curseforge app version 1.256.0.21056 6. My brother is using a Dell laptop from 6 years ago running Windows 10 (If you think more info on this would help, please ask as I do have it. I'm just choosing not to put it here for now). 7. I have reinstalled the curseforge app and installed Minecraft version 1.20.1. I have not reinstalled Minecraft or forge 47.3.0 but I didn't know if that would help. 8. I had an error code of 1 Please let me know if there is anything else that I am missing that you would like me to add to this post/add in a comment! Lastly, many thanks in advance to whoever can help! ------------- LOG FILE (latest.log) ------------- (from /Users/<NAME OF USER>/cursforge/minecraft/Instances/<THE NAME OF MY EMPTY MODPACK>/logs/latest.log) (This was made after running an empty modpack with same versions for all apps) ("[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/hxXvGGEK ------------- DEBUG.LOG (I realized that I should have put this here first after I had done all of the work on putting latest.log in) -------------------- (again, "[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/Fmh8GHYs
    • Pastebin... https://pastebin.com/Y3iZ85L5   Brand new profile, does not point to a mod as far as I can tell, my fatal message just has something about mixins. Don't know much about reading logs like this, but am genuinely stuck, please help. Java updated, pc restarted.
    • I was playing minecraft, forge 47.3.0 and 1.20.1, but when i tried to play minecraft now only crashes, i need help please. here is the crash report: https://securelogger.net/files/e6640a4f-9ed0-4acc-8d06-2e500c77aaaf.txt
  • Topics

×
×
  • Create New...

Important Information

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