Jump to content

Trying to create an event where a player holds a custom item


RBHB16

Recommended Posts

Hey guys,

I am trying to make an event as a test to see if I am properly firing events. I am new to forge so it is throwing me off a little.

 

I am not sure if I am just using the wrong event (playerinteractevent) and I should use a different one, or I just didn't do something in initializing my event or whatever it would be. If someone could help, that'd be great.

 

CommonProxy class(I link it with my main, so the info is in proxies but is called by the main):

package me.redstery11.dm.proxy;

import me.redstery11.dm.Events;
import me.redstery11.dm.Recipies;
import me.redstery11.dm._Items;
import me.redstery11.dm.theItems.Phone;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;

public class CommonProxy {
Events handler = new Events();


@EventHandler
public void preInit(FMLPreInitializationEvent e)
{
	MinecraftForge.EVENT_BUS.register(handler);
	_Items.preinit();

}
@EventHandler
public void Init(FMLInitializationEvent e)
{
	Recipies.init();
	MinecraftForge.EVENT_BUS.register(new Phone());

}

@EventHandler
public void postInit(FMLPostInitializationEvent e){

}

}

 

The events class:

The first problem I came up with was that an Itemstack cannot be compared to an item, so I went around it, but I am not sure if that worked.

package me.redstery11.dm;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public class Events {

@SubscribeEvent
public void onRightClick(PlayerInteractEvent e)
{
	EntityPlayer p = e.getEntityPlayer();
	if(p.inventory.getCurrentItem() != null)
	{
		if(p.inventory.getCurrentItem() == new ItemStack(_Items.cell_phone))
		{
			p.setFire(5);
		}
	}
}

}

Link to comment
Share on other sites

if(p.inventory.getCurrentItem() == new ItemStack(_Items.cell_phone))

Sorry, but that will never be true, because ItemStacks are not singletons like items or blocks.

You can draw parallels with this: If [this pebble from here] is [this pebble from over there]... They can never be the same, be cause they -aren't- the same.

To get the item from an itemstack, use

ItemStack#getItem

. Never create a new instance to compare.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Link to comment
Share on other sites

Thanks for the response. I changed up the code a little, but now the problem is it is saying I cannot make a static reference to a non-static method, so what I did was make an instance of my items class so I can call cell phone into the if statement. I still am getting the error, so does that mean I need to fix up my items class to make cell_phone non static?

 

package me.redstery11.dm;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public class Events {

public _Items c = new _Items();


@SubscribeEvent
public void onRightClick(PlayerInteractEvent e)
{
	EntityPlayer p = e.getEntityPlayer();
	if(p.inventory.getCurrentItem() != null)
	{
		if(EntityItem.getEntityItem().getItem().equals(c.cell_phone))
		{
			p.setFire(5);
		}
	}
}

}

Link to comment
Share on other sites

MinecraftForge.EVENT_BUS.register(new Phone());

 

What the..?

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

Don't worry about that, it was from when I first started working on the event. I used to have a class called phones but got rid of it and made an events class instead and never removed it.

First thing is first do you know Java? If you do explain what a static reference is...

EntityItem.getEntityItem()

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

I do know what a static reference is. Basically having something as static lets you use it all over without instantiating it.

 

Update:

I was able to create an if statement, but I get an error when holding the "cell phone"

 

The code:

 

 

package me.redstery11.dm;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public class Events {

@SubscribeEvent
public void onRightClick(PlayerInteractEvent e)
{
	EntityPlayer p = e.getEntityPlayer();
	ItemStack hand = p.getActiveItemStack();
	if(hand.getItem() != null)
	{
		if(hand.getItem() == _Items.cell_phone)
		{
			p.setFire(5);
		}
	}
}

}

 

 

 

The error:

 

Thread: Client thread
Stacktrace:
at me.redstery11.dm.Events.onRightClick(Events.java:15)
at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_6_Events_onRightClick_PlayerInteractEvent.invoke(.dynamic)
at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:68)
at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:159)
at net.minecraftforge.common.ForgeHooks.onRightClickBlock(ForgeHooks.java:992)
at net.minecraft.client.multiplayer.PlayerControllerMP.processRightClickBlock(PlayerControllerMP.java:418)
at net.minecraft.client.Minecraft.rightClickMouse(Minecraft.java:1603)
at net.minecraft.client.Minecraft.processKeyBinds(Minecraft.java:2281)
at net.minecraft.client.Minecraft.runTickKeyboard(Minecraft.java:2058)

-- Affected level --
Details:
Level name: MpServer
All players: 1 total; [EntityPlayerSP['Player359'/229, l='MpServer', x=-240.98, y=76.00, z=212.47]]
Chunk stats: MultiplayerChunkCache: 49, 49
Level seed: 0
Level generator: ID 00 - default, ver 1. Features enabled: false
Level generator options: 
Level spawn location: World: (-244,64,148), Chunk: (at 12,4,4 in -16,9; contains blocks -256,0,144 to -241,255,159), Region: (-1,0; contains chunks -32,0 to -1,31, blocks -512,0,0 to -1,255,511)
Level time: 92545 game time, 92545 day time
Level dimension: 0
Level storage version: 0x00000 - Unknown?
Level weather: Rain time: 0 (now: false), thunder time: 0 (now: false)
Level game mode: Game mode: creative (ID 1). Hardcore: false. Cheats: false
Forced entities: 4 total; [EntitySkeleton['Skeleton'/139, l='MpServer', x=-239.49, y=68.69, z=203.53], EntitySpider['Spider'/138, l='MpServer', x=-240.50, y=14.00, z=197.50], EntityBat['Bat'/369, l='MpServer', x=-231.90, y=26.96, z=206.84], EntityPlayerSP['Player359'/229, l='MpServer', x=-240.98, y=76.00, z=212.47]]
Retry entities: 0 total; []
Server brand: fml,forge
Server type: Integrated singleplayer server
Stacktrace:
at net.minecraft.client.multiplayer.WorldClient.addWorldInfoToCrashReport(WorldClient.java:450)
at net.minecraft.client.Minecraft.addGraphicsAndWorldToCrashReport(Minecraft.java:2779)
at net.minecraft.client.Minecraft.run(Minecraft.java:435)
at net.minecraft.client.main.Main.main(Main.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at net.minecraftforge.gradle.GradleStartCommon.launch(GradleStartCommon.java:97)
at GradleStart.main(GradleStart.java:26)

 

 

 

Link to comment
Share on other sites

ItemStack hand = p.getActiveItemStack();
	if(hand.getItem() != null)
	{

The error is a null exception right?

 

See you get an ItemStack "hand" which is player.getActiveItemStack()

 

the error you made is you reach into the object to check to see if it's null. Which is a no no you should have:

 

ItemStack hand = p.getActiveItemStack();

if(hand) != null)

{

 

When checking for "nulls" you check the direct object you got, reaching in to check is a big no.

 

So your full method should look like:

 

@SubscribeEvent
public void onRightClick(PlayerInteractEvent e)
{
	EntityPlayer p = e.getEntityPlayer();
	ItemStack hand = p.getActiveItemStack();
	if(hand != null) //Check to make sure the ItemStack gotten is not null.
	{
		if(hand.getItem() == _Items.cell_phone) // this is correct, well as long as you registered the item #cell_phone correctly 
		{
			p.setFire(5); //Honestly I prefer Console.out().Println("Am I holding a Phone?!?"); rather than directly causing things to happen
		}
	}
}

 

Link to comment
Share on other sites

ItemStack hand = p.getActiveItemStack();
	if(hand.getItem() != null)
	{

The error is a null exception right?

 

See you get an ItemStack "hand" which is player.getActiveItemStack()

 

the error you made is you reach into the object to check to see if it's null. Which is a no no you should have:

 

ItemStack hand = p.getActiveItemStack();

if(hand) != null)

{

 

When checking for "nulls" you check the direct object you got, reaching in to check is a big no.

 

So your full method should look like:

 

@SubscribeEvent
public void onRightClick(PlayerInteractEvent e)
{
	EntityPlayer p = e.getEntityPlayer();
	ItemStack hand = p.getActiveItemStack();
	if(hand != null) //Check to make sure the ItemStack gotten is not null.
	{
		if(hand.getItem() == _Items.cell_phone) // this is correct, well as long as you registered the item #cell_phone correctly 
		{
			p.setFire(5); //Honestly I prefer Console.out().Println("Am I holding a Phone?!?"); rather than directly causing things to happen
		}
	}
}

 

 

Hmmm. Well I tried that and ran a debug. It seems that when I hold the cell phone, the event is registered, but once it gets to that if(hand != null), the result is always null and doesn't move on to the other if statements even if I am holding the cell phone. Not sure what is causing this to happen.. could it be because its a custom item?

Link to comment
Share on other sites

Don't subscribe to

PlayerInteractEvent

directly, use the appropriate sub-event (

PlayerInteractEvent.RightClickItem

in this case).

 

EntityLivingBase#getActiveItemStack

only returns a non-

null

value if the entity is actively using an item like a bow or shield. Use

PlayerInteractEvent#getItemStack

to get the

ItemStack

that the event was fired for. Use

EntityLivingBase#getHeldItemMainhand

,

EntityLivingBase#getHeldItemOffhand

or

EntityLivingBase#getHeldItem

to get an entity's held item when it hasn't been provided for you.

 

Events should generally only be used for external objects (i.e. items, blocks, etc. created by vanilla or other mods); you should prefer to override the appropriate callback method when possible (

Item#onItemRightClick

).

 

 

you can try

ItemStack hand = p.inventory.getCurrentItem();

 

That will only ever return the item in the player's main hand, but the event may have been fired for the off hand.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

I do know what a static reference is. Basically having something as static lets you use it all over without instantiating it.

 

While true, it completely misses the point.

A static reference can only be used with non-instances.  An instance reference cannot use static references.

You can pass instances to a static method, but a static method does not magically contain the information from an instance just because they're the same class.

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've moved onto adding more code and I am stuck again...

 

I am thinking about making a GUI for the cell phone when the player holds the item and right clicks. I think everything works up until I try to check to see if the player right clicked. I am going to add another event to check if the player right clicked the item while looking at a block, since I am limited to either checking to see if the player right clicked in the air or right clicked looking at a block. This is what I have so far:

 

Also, any help is appreciated

 

 

package me.redstery11.dm;

import java.awt.Event;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickEmpty;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import scala.Console;

public class Events {

public enum Action
{
	RIGHT_CLICK_AIR,
	RIGHT_CLICK_BLOCK;
}

@SubscribeEvent
public void onRightClickPhone(PlayerInteractEvent.RightClickItem e)
{
	EntityPlayer p = e.getEntityPlayer();
	ItemStack hand = p.inventory.getCurrentItem();
	if(hand != null)
	{
		if(hand.getItem() == _Items.cell_phone)
		{
			if (e.getHand().equals(Action.RIGHT_CLICK_AIR))
			{
				Console.out().println("It works!");
			}		

		}
	}
}

}

 

 

Link to comment
Share on other sites

import java.awt.Event;

You should very rarely need to import or use any AWT classes with the possible exception of

Color

, which can be used to get the RGB integer of a colour.

 

import org.lwjgl.input.Keyboard;

import org.lwjgl.input.Mouse;

You can't use LWJGL or read player input in common code, these can only be done on the client.

 

import scala.Console;

Why are you using Scala's

Console

class?

 

public enum Action

{

RIGHT_CLICK_AIR,

RIGHT_CLICK_BLOCK;

}

You shouldn't need this enum.

 

if (e.getHand().equals(Action.RIGHT_CLICK_AIR))

PlayerInteractEvent#getHand

returns an

EnumHand

. Checking if an

EnumHand

is equal to an

Action

makes no sense and will never be

true

.

 

PlayerInteractEvent.RightClickBlock

is fired when a player right clicks a block.

PlayerInteractEvent.RightClickItem

is fired when a player right clicks air while holding an item.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • My minecraft keeps crashing with this modpack I made and I don't understand why https://mclo.gs/zE9HYYM
    • After uninstalling this mod, everything works! Thanks!
    • I had been playing on this fabric server for about a month with some friend and one day it just stopped starting, can anyone help me understand what the cause is? https://mclo.gs/2jop3r5    
    • The mobs are moving normally for a second, then freeze, then go back to normal, and this repeats. I describe this as mob lag, bc they stutter as if they were lagging. I don't have the best wifi, but that shouldn't matter since its 10mbps which is enough for a server. I have 8 gigs of ram for it, no optimizations have worked, if there is anything more you may need to help lmk, ill describe. The modlist is pretty hefty: VS_ClockworkSurvivalSupportV1.4 aether-1.20.1-1.2.0-neoforge.jar alexsdelight-1.5.jar alexsmobs-1.22.7.jar appleskin-forge-mc1.20.1-2.5.1.jar backpacked-forge-1.20.1-2.2.5.jar balm-forge-1.20.1-7.2.1.jar bettervillage-forge-1.20.1-3.2.0.jar BiomesOPlenty-1.20.1-18.0.0.598.jar botarium-forge-1.20.1-2.3.2.jar CGM-Unofficial-1.4.11+Forge+1.20.1.jar citadel-2.5.2-1.20.1.jar clockwork-1.20.1-0.1.2-forge-05f5d5fbbb.jar configured-forge-1.20.1-2.2.2.jar connectivity-1.20.1-4.9.jar create-1.20.1-0.5.1.f.jar create-new-age-forge-1.20.1-1.1.2.jar createarmoryv0.6.1n.jar createbigcannons-forge-1.20.1-0.5.3.b.jar createchunkloading-1.6.0-forge.jar createdeco-2.0.1-1.20.1-forge.jar createdieselgenerators-1.20.1-1.2h.jar createendertransmission-2.0.7-1.20.1.jar create_misc_and_things_ 1.20.1_4.0A.jar cristellib-1.1.5-forge.jar cupboard-1.20.1-2.3.jar curios-forge-5.7.0+1.20.1.jar destroy-1.20.1-0.8.jar Dungeon Crawl-1.20.1-2.3.14.jar FallingTree-1.20.1-4.3.4.jar FarmersDelight-1.20.1-1.2.4.jar framework-forge-1.20.1-0.6.26.jar geckolib-forge-1.20.1-4.4.2.jar InsaneLib-1.12.1-mc1.20.1.jar Jade-1.20.1-forge-11.8.0.jar jei-1.20.1-forge-15.3.0.4.jar journeymap-1.20.1-5.9.18-forge.jar JustEnoughResources-1.20.1-1.4.0.247.jar kotlinforforge-4.10.0-all.jar l2library-2.4.23.jar libraryferret-forge-1.20.1-4.0.0.jar macawsbridgesbop-1.20-1.1.jar mcw-bridges-2.1.0-mc1.20.4forge.jar moonlight-1.20-2.9.17-forge.jar morevillagers-forge-1.20.1-5.0.0.jar Mo_ZombiesWave-1.20.1-0.1.0-forge.jar NaturesCompass-1.20.1-1.11.2-forge.jar Placebo-1.20.1-8.6.1.jar refinedstorage-1.12.4.jar soundphysics-forge-1.20.1-1.1.2.jar spark-1.10.53-forge.jar stealing_villagers-forge-1.20.1-1.0.0.jar s_a_b-1.3.0_1.20.1.jar takesapillage-1.0.3-1.20.1.jar TerraBlender-forge-1.20.1-3.0.1.4.jar tombstone-1.20.1-8.6.2.jar Towns-and-Towers-1.12-Fabric+Forge.jar twilightforest-1.20.1-4.3.2145-universal.jar valkyrienskies-120-2.1.3-beta.1.jar veinmining-forge-1.3.0+1.20.1.jar waystones-forge-1.20-14.1.3.jar YungsApi-1.20-Forge-4.0.3.jar YungsBetterDesertTemples-1.20-Forge-3.0.3.jar YungsBetterDungeons-1.20-Forge-4.0.3.jar YungsBetterEndIsland-1.20-Forge-2.0.5.jar YungsBetterJungleTemples-1.20-Forge-2.0.4.jar YungsBetterMineshafts-1.20-Forge-4.0.4.jar YungsBetterNetherFortresses-1.20-Forge-2.0.5.jar YungsBetterOceanMonuments-1.20-Forge-3.0.4.jar YungsBetterStrongholds-1.20-Forge-4.0.3.jar YungsBetterWitchHuts-1.20-Forge-3.0.3.jar YungsBridges-1.20-Forge-4.0.3.jar zaynens_leather_from_rotten_flesh_mod_1.20.1.jar
  • Topics

×
×
  • Create New...

Important Information

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