Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[Solved] Increase the use time of a tool.


Recommended Posts

Hey all, I'm trying to find a way to decrease the interval in which onItemUse() is fired on an item. For my application, I'm trying to increase the use time of my overwritten vanilla shears on a certain block that yields drops after you shear it. I want it to shear as fast as someone would punch out a bunch of tall grass.

 

Here's my code in attempt to set the swinging time to zero when detecting the block being right clicked in the RightClickBlock event, sadly it doesn't work:

@SubscribeEvent
    public void farmBlock(PlayerInteractEvent.RightClickBlock event)
    {
        if(event.getPlayer().getHeldItem(event.getHand()).getItem().equals(Items.SHEARS) && event.getWorld().getBlockState(event.getPos()).equals(RegistryHandler.MY_BLOCK.get().getDefaultState())){
            System.out.println("My block was right clicked!"); //Testing purposes.
            event.getPlayer().swingProgressInt = 1;
        }
    }

 

I also have code in the onItemUse() function in my new vanilla shears class that allows the player to shear my block (turns it into another block) much like using an axe to right click will shave wood. Everything works the way that it should, I just want to decrease the time in which the item is used. :)

 

Like said before, I can change the shears however I want, as long as this works. Any pointers?

 

Thanks a ton!

Edited by CommandCore
Issue Still Exists.
Link to post
Share on other sites
1 hour ago, diesieben07 said:

I think this is Minecraft#rightClickDelayTimer. You can subscribe to TickEvent.ClientTickEvent, check for Phase.START and set it to 0 to forcibly disable this cooldown.

Okay, so I'll set Minecraft#rightClickDelayTimer to 0 through reflection, but won't this set the variable globally? Because TickEvent.ClientTickEvent doesn't have a "player" variable or "getPlayer()" method. 

Link to post
Share on other sites
2 minutes ago, diesieben07 said:

Minecraft#player is the player that you are "controlling".

Okay cool, I did the reflection straight in the PlayerInteractEvent.RightClickBlock method though, and everything's working A-Okay. Thanks for the help man. Here's my code for anyone that views this thread:

 

Actual Method:

@SubscribeEvent
    public void farmBlock(PlayerInteractEvent.RightClickBlock event) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
        if(event.getPlayer().getHeldItem(event.getHand()).getItem().equals(Items.SHEARS) && event.getWorld().getBlockState(event.getPos()).equals(RegistryHandler.MY_BLOCK.get().getDefaultState())){
            JavaStuff.setInstanceValue(Minecraft.getInstance(), "rightClickDelayTimer", 0);
        }
    }

 

And since I see a lot of people that don't know how to do reflection and need it done, here you go. Click the link in the comment for more ways to do it, like with static variables and stuff. Chances are you'll only be doing it with non-static variables though, since literally Minecraft itself is an instance in this situation lol:

public static void setInstanceValue(final Object classInstance, final String fieldName, final Object newValue) throws SecurityException,
            NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
        // Get the private field
        final Field field = classInstance.getClass().getDeclaredField(fieldName);
        // Allow modification on the field
        field.setAccessible(true);
        // Sets the field to the new value for this instance
        field.set(classInstance, newValue);

    }

    // Via https://blog.sevagas.com/Modify-any-Java-class-field-using-reflection
    //Thanks Sevagas!

 

Link to post
Share on other sites
Just now, CommandCore said:

I did the reflection straight in the PlayerInteractEvent.RightClickBlock method though

You cannot do that. That is a server-side event.

 

Do not get the Field instance every time, get it once and store it in a static final field. Then also note that Minecraft fields will be obfuscated outside the development environment, so you need to use ObfuscationReflectionHelper and give it the SRG name instead of plain reflection.

Link to post
Share on other sites
31 minutes ago, diesieben07 said:

You cannot do that. That is a server-side event.

 

Do not get the Field instance every time, get it once and store it in a static final field. Then also note that Minecraft fields will be obfuscated outside the development environment, so you need to use ObfuscationReflectionHelper and give it the SRG name instead of plain reflection.

 

I see. Okay, so I did this, and it works, but am I doing it wrong still?:

 

private static boolean brokeMyBlock = false;

    @SubscribeEvent
    public void onClickTickEvent(TickEvent.ClientTickEvent event){

        PlayerEntity player = Minecraft.getInstance().player;

        if(brokeMyBlock){
            System.out.println("Sheared Block");
            ObfuscationReflectionHelper.setPrivateValue(Minecraft.class, Minecraft.getInstance(), 0, "rightClickDelayTimer");
            brokeMyBlock = false;
        }
    }

    @SubscribeEvent
    public void farmMyBlock(PlayerInteractEvent.RightClickBlock event) {
        if(event.getPlayer() == Minecraft.getInstance().player){
            if(event.getPlayer().getHeldItem(event.getHand()).getItem().equals(Items.SHEARS) && event.getWorld().getBlockState(event.getPos()).equals(RegistryHandler.MY_BLOCK.get().getDefaultState())){
                brokeMyBlock = true;
            }
        }
    }

 

32 minutes ago, diesieben07 said:

Do not get the Field instance every time, get it once and store it in a static final field.

Couldn't see how to fit this in, because from what I saw, ObfuscationReflectionHelper didn't have a variation that uses a Field.

 

But I did put some code for it, don't know how to put the puzzles pieces together though with what I did above:

private static final Field field = rightClickDelayTimerField();

    private static Field rightClickDelayTimerField() {
        try {
            return Minecraft.getInstance().getClass().getDeclaredField("rightClickDelayTimer");
        } catch (NoSuchFieldException e) {
            return null;
        }
    }

 

Link to post
Share on other sites
1 minute ago, CommandCore said:

PlayerEntity player = Minecraft.getInstance().player;

You cannot do this. The player can and will change.

 

2 minutes ago, CommandCore said:

private static boolean brokeMyBlock = false;

You cannot do this. You are reaching across logical sides here.

 

2 minutes ago, CommandCore said:

Couldn't see how to fit this in, because from what I saw, ObfuscationReflectionHelper didn't have a variation that uses a Field.

ObfuscationReflectionHelper.findField

Link to post
Share on other sites
1 hour ago, diesieben07 said:

You cannot do this. The player can and will change.

 

You cannot do this. You are reaching across logical sides here.

 

ObfuscationReflectionHelper.findField

 

I believe this new version covers everything you said. I used an attached player capability for the boolean.

private static final Field field = ObfuscationReflectionHelper.findField(Minecraft.class, "rightClickDelayTimer");

    @SubscribeEvent
    public void onClientTickEvent(TickEvent.ClientTickEvent event) throws IllegalAccessException {

        if(event.phase == TickEvent.Phase.START)
        {
            try {

                if(CustomCapabilities.getPlayer(Minecraft.getInstance().player).getVariable("string", "HasBrokenMyBlock").equals("true")){
                    field.setInt(Minecraft.getInstance(), 0);
                    CustomCapabilities.getPlayer(Minecraft.getInstance().player).setVariable("HasBrokenMyBlock", "false");
                }

            } catch (NullPointerException e) {}
        }
    }

    @SubscribeEvent
    public void farmBlock(PlayerInteractEvent.RightClickBlock event) {
        if(event.getPlayer() == Minecraft.getInstance().player){
            if(event.getPlayer().getHeldItem(event.getHand()).getItem().equals(Items.SHEARS) && event.getWorld().getBlockState(event.getPos()).equals(RegistryHandler.MY_BLOCK.get().getDefaultState())){
                CustomCapabilities.getPlayer(event.getPlayer()).setVariable("HasBrokenMyBlock", "true");
            }
        }
    }

 

Everthing works, but a server instance isn't running because it doesn't like the ClientTickEvent: "Attempted to load class net/minecraft/client/entity/player/ClientPlayerEntity for invalid dist DEDICATED_SERVER"

 

Tried to use regular TickEvent and it gave me the same error. :/

Link to post
Share on other sites
2 minutes ago, CommandCore said:

private static final Field field = ObfuscationReflectionHelper.findField(Minecraft.class, "rightClickDelayTimer");

You need to use the SRG name, this won't work outside the development environment.

 

3 minutes ago, CommandCore said:

CustomCapabilities.getPlayer(Minecraft.getInstance().player).getVariable("string", "HasBrokenMyBlock").equals("true")

What...? What... Just... what is this?

 

3 minutes ago, CommandCore said:

if(event.getPlayer() == Minecraft.getInstance().player){

This will crash on a server, as the server has no idea about the Minecraft class.

 

3 minutes ago, CommandCore said:

"Attempted to load class net/minecraft/client/entity/player/ClientPlayerEntity for invalid dist DEDICATED_SERVER"

Client-only events must be in a separate @EventBusSubscriber class with Dist.CLIENT passed to @EventBusSubscriber.

Link to post
Share on other sites
36 minutes ago, diesieben07 said:

You need to use the SRG name, this won't work outside the development environment.

 

What...? What... Just... what is this?

 

This will crash on a server, as the server has no idea about the Minecraft class.

 

Client-only events must be in a separate @EventBusSubscriber class with Dist.CLIENT passed to @EventBusSubscriber.

Alright, put this in a class that's only for client events.

 

private static final Field field = ObfuscationReflectionHelper.findField(Minecraft.class, "field_71467_ac");

    @SubscribeEvent

    public static void onClientTickEvent(TickEvent.ClientTickEvent event) throws IllegalAccessException {

        if(event.phase == TickEvent.Phase.START)
        {
            try {

                if(CustomCapabilities.getPlayer(Minecraft.getInstance().player).getVariable("string", "HasBrokenMyBlock").equals("true")){
                    field.setInt(Minecraft.getInstance(), 0);
                    CustomCapabilities.getPlayer(Minecraft.getInstance().player).setVariable("HasBrokenMyBlock", "false");
                }

            } catch (NullPointerException e) {}
        }
    }

 

I removed

38 minutes ago, diesieben07 said:

if(event.getPlayer() == Minecraft.getInstance().player){

here is the new code that stayed in that class:

 

@SubscribeEvent
    public void farmBlock(PlayerInteractEvent.RightClickBlock event) {
        if(event.getPlayer().getHeldItem(event.getHand()).getItem().equals(Items.SHEARS) && event.getWorld().getBlockState(event.getPos()).equals(RegistryHandler.MY_BLOCK.get().getDefaultState())){
            CustomCapabilities.getPlayer(event.getPlayer()).setVariable("HasBrokenMyBlock", "true");
        }
    }

 

And

39 minutes ago, diesieben07 said:

CustomCapabilities.getPlayer(Minecraft.getInstance().player).getVariable("string", "HasBrokenMyBlock").equals("true")

is the custom capability system of mine that I was talking about. You can think of it as setting a value on a capability that is attached to PlayerEntitys. The real variable-setting stuff is buried under a bunch of static methods for convenience.

 

This seems to be the only way to put a boolean value on my player that really just functions to link the functions of the RightClickBlock event to the ClientTickEvent. I suppose if there was a better way to link them, I wouldn't have to do this.

 

Everything works, even when the client logged into the server.

Link to post
Share on other sites

That is still reaching across logical sides.

You don't need this "capability" stuff... If you do need to store data on players, use actual Forge capabilities.

 

You need to check in RightClickBlock if you are on the client.

Link to post
Share on other sites

Got it. Moved it to the client event class. Everything seems to be working.

 

5 minutes ago, diesieben07 said:

You don't need this "capability" stuff... If you do need to store data on players, use actual Forge capabilities.

It is a Forge capability, with an interface, class, provider, and storage, along with a AttachCapabilitiesEvent<Entity> called in a class to attach it to PlayerEntity's. Sorry if that wasn't clear in my last post. Unless you're talking about a capability that is already in Forge?

Link to post
Share on other sites
Just now, diesieben07 said:

Okay so it is a normal capability. Then why are you not just making normal fields in it that you put values in?

Because I wanted the ability to add custom values when setting them. For example, I wouldn't have to go into the capability and add a new variable, I can just say "Set the variable 'Working' to 'true'."

And if its trying to get a variable that hasn't been set yet, it'll return 0 or "" depending on what kind of variable I set it as, (Notice the "string" argument.)

 

Its sort of mimicking the stuff you can do with getPersistentData() on an entity. TLDR; Convenience. ¯\_(ツ)_/¯

Link to post
Share on other sites
2 minutes ago, diesieben07 said:

So you are bypassing the nice typesystem that Java gives you, for... convenience.

This is a pretty bad antipattern.

 

https://wiki.c2.com/?StringlyTyped

Ah, I see. So unnecessary casting and assigning of variables via strings is the culprit of this bad practice? Does this contribute to inefficiency? From that site you posted, that seems to be the case.

Link to post
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.

Guest
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

    • Please post your server log, it should give a clue what's going on.
    • It looks like you may be trying to reply to someone's support post, you instead you created a new one.
    • compactstorage-1.16.5-5.1b17.jarcarryon-1.16.5-1.15.5.15.jarAdHooks-1.16.4-6.1.5.0-build.0124.jarXaerosWorldMap_1.14.1_Forge_1.16.5.jarXaeros_Minimap_21.10.0.3_Forge_1.16.5.jartrashcans-1.0.10-mc1.16.5.jarSuperTools-1.2_1.16.5.jarSpartanShields-1.16.5-2.1.2.jarrandomite-1.16.4-1.0.1.jaroverloadedarmorbar-5.1.0.jaroresplusmod_1.16.5,0.1.0.jarturtle_armor-1.3.4.jartoyguns-0.1-1.16.4.jartoughnessbar-6.1.jartorchmaster-2.3.7.jarToast-Control-1.16.4-4.3.1.jartitanium-1.16.5-3.2.8.4-10.jarthermal_expansion-1.16.4-1.2.0.jartheoneprobe-1.16-3.1.4.jarthedragonlib-1.16.3-1.1.0.jarswingthroughgrass-1.16.4-1.5.3.jarsuper+armor-5.0.4(EN).jarStorageDrawers-1.16.3-8.2.2.jarsteveGolemMod_1.3.0.jarSteelArmory.jarSoulBound-1.1.3-1.16.5.jarSimplyBetter.jarSimple guns reworked 1.16.5 v1.4.jarsilent-lib-1.16.3-4.9.6.jarRunelic-1.16.5-7.0.1.jarrftoolsbase-1.16-2.0.10.jarReAuth-1.16-Forge-3.9.3.jarrandompatches-2.4.4-forge.jarprecious_armor-1.16.5.jarPlacebo-1.16.4-4.5.0.jarPatchouli-1.16.4-51.jaroverloadedarmorbar-5.1.0.jarOreExcavation-1.8.157.jarOp Armor Plus 1.16.5 0.6.jarobserverlib-1.16.5-1.5.3.jarobfuscate-0.6.2-1.16.3.jarnetheritehorsearmor-1.7.jarNeat 1.7-27.jarNaturesCompass-1.16.5-1.9.0.jarMouseTweaks-2.14-mc1.16.2.jarMorpheus-1.16.5-4.2.70.jarMoreOresArmorsAndTools 1.2.5.jarMoreArmor-1-4-0.jarMekanismTools-1.16.5-10.0.21.448.jarMekanismGenerators-1.16.5-10.0.21.448.jarmcjtylib-1.16-5.0.19.jarMantle-1.16.5-1.6.103.jarMachineBoy's ArmorTool v1.2b1.jarJustEnoughResources-1.16.5-0.12.1.121.jarJEITweaker-1.16.5-1.0.1.28.jarjei-1.16.5-7.7.0.106.jarJ0T0S0 Weapons 1.0.0.jarironchest-1.16.4-11.2.10.jarillagersweararmor-1.0.4.jariChunUtil-1.16.5-10.4.1.jarhitscan-1.0.1.jarHandyGuns2.0.jargunswithoutroses-1.16.5-1.0.9.jarGuns'N'Glory-2.0.jarGuns and Rifes.jarftb-backups-2.1.1.6.jarForgeEndertech-1.16.4-7.1.0.0-build.0075.jarFluxNetworks-1.16.5-6.1.7.12.jarFastWorkbench-1.16.4-4.5.1.jarFastLeafDecay-v25.jarFastFurnace-1.16.4-4.4.0.jarfabric-api-0.35.0+1.16.jarExtraArmor-1.12.1-1.16.5.jarEnderStorage-1.16.4-2.7.1.166-universal.jarEnchantmentDescriptions-1.16.5-7.0.8.jarEnameledArmor-1.16.2-1.0.0.8.jaremeraldtoolsandarmor1.16.x.jarEmeraldArmorAndTools.jarelevatorid-1.16.5-1.7.13.jarDiceMC-TieredArmor-1.16.5-1.1a.jarDefaultOptions_1.16.5-12.2.1.jarDecraftHorseArmor-1.16.5-r1.jarDarkUtilities-1.16.5-8.0.10.jarCyclopsCore-1.16.5-1.11.7.jarCurious Armor Stands-1.16.5-2.1.1.jarcurios-forge-1.16.5-4.0.5.2.jarCucumber-1.16.4-4.1.10.jarCTM-MC1.16.1-1.1.2.6.jarCraftingTweaks_1.16.5-12.2.1.jarCraftableChainmail-1.16.5-1.1.0.jarcraftable_chainmail_1.16.5.jarOresAboveDiamonds-1.16.4-v6.3.3.jarCraftable Saddle and Horse Armors.jarCosmeticArmorReworked-1.16.5-v3a.jarCookingForBlockheads_1.16.5-9.3.2.jarControlling-7.0.0.23.jarcomforts-forge-1.16.5-4.0.0.4.jarColtCosmeticArmorMod-1.2.5.jarCodeChickenLib-1.16.4-3.5.1.408-universal.jarClumps-6.0.0.25.jarcitadel-1.7.1-1.16.5.jarchiselsandbits-0.3.4-RELEASE.jarcarryon-1.16.5-1.15.5.15.jarbuildinggadgets-1.16.5-3.8.0.jarBookshelf-1.16.5-10.1.11.jarBomb and guns.jarBlockArmor-1.16.5-2.6.2.jarBetterMineshafts-Forge-1.16.4-2.0.4.jarBetterHorseArmor-1.16.3-1.0.1.1.jarBetterAdvancements-1.16.5-0.1.0.108.jarBedrock Armor 1.16.5-1.0.2.jarAutoRegLib-1.6-49.jararmor-visibility-2.0.1-forge.jarArmorUp-1.0.5-BETA.jarArmorUnlocked-1.16.3-1.0.1.jararmorunder-mc1.16.5-2.0b11.jararmor-stand-editor-1.1.0.jarArmorPoser-1.16.5-1.0.1.jararmorpointspp-1.16.5-2.0.0.jararmorhotswap-1.16-1.8.jarArmoredElytra-1.0.8.jararmorcurve-2.3.jarAquaculture-1.16.5-2.1.19.jarAppleSkin-mc1.16.2-forge-1.0.14.jarApotheosis-1.16.4-4.6.1.jarAncientGuns_3.2_1.16.4.jarAkashicTome-1.4-16.jar1.7.4.1-1.16.5ATOp.jar[1.16.5] BobLib-0.2.0.jar[1.16.5] Armor Status HUD-1.4.0.jarEmerald armor and tools 1.15.16 v3.jarYungsApi-1.16.4-Forge-6.jaryeni modum.jarxnet-1.16-3.0.13.jarwolveswitharmor-1.1.0-1.16.2.jarWaystones_1.16.5-7.6.2.jarvisiblearmorslots-2.0-1.16.5.jarNeat 1.7-27.jarNaturesCompass-1.16.5-1.9.0.jarMoreOresInONE-1.2_1.16.5.jarmcw-windows-1.0.3-mc1.16.5.jarmcw-bridges-1.0.5-mc1.16.5-4.jarlongfallboots-1.6.0a.jarJustEnoughResources-1.16.5-0.12.1.121.jarjei-1.16.5-7.7.0.106.jarForgeEndertech-1.16.4-7.1.0.0-build.0075.jarextcaves-2.4.jarcurios-forge-1.16.5-4.0.5.2.jarcorpse-1.16.5-1.0.5.jarAdHooks-1.16.4-6.1.5.0-build.0124.jar
    • Dude, then try to click the down arrow near "Open" then select   Java(TM) Platform SE binary then it should work or if it doesn't work then it means you don't have Java or you computer is broken.
    • I have created a Container with a FluidTank Slot. In order to draw this on the Screen, I need to get the texture of the Fluid and draw it transparently in the case of water. 1. How do I get the texture of a fluid? 2. How can I draw transparent (and animate) water?
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.