Jump to content

Getting EntityPlayer parameter outside of the method itself


Flenix

Recommended Posts

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

width=463 height=200

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

My mods (Links coming soon)

Cities | Roads | Remula | SilvaniaMod | MoreStats

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

    • LUCONETWORK  LucoNetwork is a brand new SkyBlock and Prisons server and we are looking for staff & Developers. We are always in need of players and we want to make this a very fun and enjoyable server for all to enjoy. We are welcoming ALL. We hope to be the best and we want your support to make our servers better. Thank you so much for reading this. About the server: We are currently working on getting the SkyBlock server up and released. Then we will be working on some more servers to get them up. We will be bug fixing once the server released & working hard to get updates out to Skyblock too. we are striving to be the best network. What game modes can I hope to see inside Luco Network?  Prisons  Lifesteal  SkyBlock  Survival / Earth SMP Why should I join LucoNetwork? We strive to listen to our player base, we want to work for our player base.  We strive to make the best & enjoyable servers for all to enjoy. Our links: https://discord.gg/fmd4SrzdWt
    • When i try to launch Minecraft Java 1.20.1 forge with mods (82 mods),on start it loaded all mods,but at end Java just crashed.  p.s i allocated 8GB ram for minecraft and i didn't runned another instance.Log file pp.s I use ATlauncher   Environment: Organising filesystem [24/04/2024 23:40:08 PM] ATLauncher Version: 3.4.36.3 [11ae0b2334c236e93ee8128de980952b2a1b8900] [24/04/2024 23:40:08 PM] App Arguments: ["--install-method=aur","--no-launcher-update"] [24/04/2024 23:40:08 PM] JVM Arguments: ["-Dawt.useSystemAAFontSettings=on","-Dswing.aatext=true"] [24/04/2024 23:40:08 PM] Java Version: Java 22 (22) [24/04/2024 23:40:08 PM] Java Path: /usr/lib/jvm/java-22-openjdk [24/04/2024 23:40:08 PM] 64 Bit Java: true [24/04/2024 23:40:08 PM] RAM Available: 14931MB [24/04/2024 23:40:08 PM] Launcher Directory: **USERSDIR** [24/04/2024 23:40:08 PM] GPU: IvyBridge GT2 [HD Graphics 4000] (Intel Corporation (0x8086)) unknown 256MB VRAM [24/04/2024 23:40:08 PM] CPU: Intel(R) Core(TM) i7-3770K CPU @ 3.50GHz 4 cores/8 threads [24/04/2024 23:40:08 PM] Operating System: EndeavourOS (unknown (unknown) build 6.8.7-arch1-1) [24/04/2024 23:40:08 PM] Bitness: 64 [24/04/2024 23:40:08 PM] Uptime: 15889 [24/04/2024 23:40:08 PM] Manufacturer: GNU/Linux
    • If you have nvidia graphics, don't touch your amd drivers, otherwise it might fix it but keep running on integrated graphics, which will result in terrible performance. For nvidia graphics, you need to tell windows and nvidia control panel that anything Minecraft related (the launcher, java, etc...) should prefer high performance graphics so that it actually uses your nvidia gpu
    • In the ever-evolving landscape of technology, the rise of cryptocurrencies and digital assets has introduced both unparalleled opportunities and unprecedented challenges. As these digital currencies become increasingly prevalent, so too does the risk of theft and loss. Yet, amidst the complexity and uncertainty, there exists a beacon of hope: ADRIAN LAMO HACKER. Technology has indeed become more sophisticated and enhanced, presenting new challenges in the realm of asset recovery. However, just as any other currency can be stolen or lost, crypto and digital assets are not beyond redemption. With the right expertise and guidance, recovery is possible and achievable. Contact ADRIAN LAMO HACKER via the website: https://adrianlamohackpro.online/ , a trusted, honest, and certified agency specializing in the retrieval of stolen or lost digital assets. In my own experience, I found myself in dire straits after falling victim to cybercriminals who absconded with a significant portion of my crypto holdings. It was a daunting situation, but I refused to succumb to despair. Upon engaging ADRIAN LAMO HACKER, their professionalism, and integrity immediately struck me, as an unwavering commitment to their clients. They deeply understand blockchain technology and utilize advanced methodologies to trace and recover lost or stolen funds. Their approach is meticulous, their expertise unparalleled, and their results speak for themselves. In a matter of days, ADRIAN LAMO HACKER successfully traced and recovered over 90% of my stolen funds, a feat I once believed to be unattainable. Their fees were fair and transparent, and communication throughout the process was nothing short of excellent. They kept me informed every step of the way, providing reassurance and guidance when I needed it most. For anyone who has fallen victim to crypto theft or loss, I wholeheartedly recommend ADRIAN LAMO HACKER. They are not just experts in their field; they are guardians of justice in the digital realm. With their assistance, you can reclaim what's rightfully yours and emerge stronger than ever before. So, if you find yourself grappling with the devastation of lost or stolen digital assets, don't despair. Reach out to ADRIAN LAMO HACKER via website: https://adrianlamohackpro.online/  / Telegram: @ADRIANLAMOHACKERTECH and let them guide you toward a brighter tomorrow.
  • Topics

×
×
  • Create New...

Important Information

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