Jump to content

Recommended Posts

Posted (edited)

I would like to implement a weapon with a unique attack mechanic. When the left click is held, the weapon starts charging. The weapon deals damage when left click is released.

How do I do this? Should I use the LeftClickBlock and LeftClickEmpty events?

Edited by LeeCrafts
Posted (edited)

I dont think you can count ticks using that event so maybe have two separate event's. First use leftClickEmpty to set an int persistent data(label this whatever) and then check in PlayerTick if you have this data tag and that Minecraft.getInstance().mouseHandler.isLeftPressed(). If so add 1 to the overall value of that tag and then in playertick check if the player has the tag but is not pressing down LMB then thats when you shoot the gun.

Note 1 Second in ticks is 20 I think or 22 i'm unsure just use a static method to convert to ticks and convert ticks to seconds

Edited by sFXprt
Posted

How is this different from what the (Cross)Bow does?

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted
11 hours ago, sFXprt said:

I dont think you can count ticks using that event so maybe have two separate event's. First use leftClickEmpty to set an int persistent data(label this whatever) and then check in PlayerTick if you have this data tag and that Minecraft.getInstance().mouseHandler.isLeftPressed(). If so add 1 to the overall value of that tag and then in playertick check if the player has the tag but is not pressing down LMB then thats when you shoot the gun.

Note 1 Second in ticks is 20 I think or 22 i'm unsure just use a static method to convert to ticks and convert ticks to seconds

Thanks, I was just hoping there would be an easier way (e.g. using methods like Item::releaseUsing), but I guess I'm gonna have to manually implement events and capabilities (and possibly sync the data to the server because the mouse handler is client side).

5 hours ago, warjort said:

How is this different from what the (Cross)Bow does?

To be honest, not THAT much different, but more difficult regardless because I have to track if left click is held, not right click. And there does not seem to be any vanilla methods in the Item class / IForgeItem interface that tracks if left click is held down.

Posted

Left click is for block breaking not item use. Block breaking has a different progress mechanic.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted (edited)

Yes, true. That's the challenge I believe. The weapon I'm trying to make is supposed to be heavy hammer, and I would think it would be a bit unfitting if I had to use right-click to attack with a melee weapon. 

Edited by LeeCrafts
Posted (edited)

My solution is in the code below. Please let me know if there is a better way.

// client events
@Mod.EventBusSubscriber(modid = ExampleMod.MODID, value = Dist.CLIENT)
public static class ClientForgeEvents {

    // To attack with the hammer, the player must hold left click for CHARGE_LIMIT ticks, and then let go.
    // A capability is attached to LocalPlayers to store the hammer charge time.
  
    // Uncomment the commented lines if you want the attack indicator bar to fill while the hammer attack is charged.
    // However, you would need access transformers for this. It becomes even more necessary to modify the LivingEntity::attackStrengthTicker field when the packet is sent to the server (see the packet class below).
    @SubscribeEvent
    public static void clientTick(TickEvent.ClientTickEvent event) {
        if (event.phase == TickEvent.Phase.END) {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            if (localPlayer != null) {
                localPlayer.getCapability(ModCapabilities.PLAYER_CAPABILITY).ifPresent(iPlayerCap -> {
                    PlayerCap playerCap = (PlayerCap) iPlayerCap;
                    boolean leftMouse = Minecraft.getInstance().mouseHandler.isLeftPressed();
                    boolean holdingHammer = localPlayer.getMainHandItem().getItem() == ModItems.HAMMER_THING.get();

                    if (!holdingHammer || !leftMouse) {
                        if (!leftMouse) {
                            if (playerCap.hammerCharge >= CHARGE_LIMIT) {
                                localPlayer.swing(InteractionHand.MAIN_HAND);
                              
                                // If an entity is in reach, it'll be hit by the hammer attack (see packet class below)
                                HitResult hitResult = Minecraft.getInstance().hitResult;
                                if (hitResult != null && hitResult.getType() == HitResult.Type.ENTITY) {
                                    int entityId = ((EntityHitResult) hitResult).getEntity().getId();
                                    PacketHandler.INSTANCE.sendToServer(new ServerboundHammerThingAttackPacket(entityId));
                                }
                            }
                        }
                        playerCap.hammerCharge = 0;
                        // if (holdingHammer) localPlayer.attackStrengthTicker = CHARGE_LIMIT;
                    }
                    else {
                        playerCap.hammerCharge = Math.min(CHARGE_LIMIT, playerCap.hammerCharge + 1);
                        // localPlayer.attackStrengthTicker = playerCap.hammerCharge;
                    }
                });
            }
        }
    }

    // cancels vanilla mining and swinging mechanics when player presses left click while holding hammer
    @SubscribeEvent
    public static void inputEvent(InputEvent.InteractionKeyMappingTriggered event) {
        if (event.isAttack()) {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            if (localPlayer != null && localPlayer.getMainHandItem().getItem() == ModItems.HAMMER_THING.get()) {
                event.setSwingHand(false);
                event.setCanceled(true);
            }
        }
    }

}

 

// packet class
public class ServerboundHammerThingAttackPacket {

    public final int targetId;

    public ServerboundHammerThingAttackPacket(int targetId) {
        this.targetId = targetId;
    }

    public ServerboundHammerThingAttackPacket(FriendlyByteBuf buffer) {
        this(buffer.readInt());
    }

    public void encode(FriendlyByteBuf buffer) {
        buffer.writeInt(this.targetId);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ServerPlayer sender = ctx.get().getSender();
            if (sender != null) {
                // This line is necessary. Otherwise attackStrengthTicker would be 0, making the attack very weak.
                // attackStrengthTicker must be set server side, hence the server bound packet.
                sender.attackStrengthTicker = CHARGE_LIMIT;
              
                Entity entity = sender.level.getEntity(this.targetId);
                if (entity != null) {
                    sender.attack(entity);
                }
            }
        });
        ctx.get().setPacketHandled(true);
    }

}

 

// and finally, the packet handler class
public class PacketHandler {

    private static final String PROTOCOL_VERSION = "1";

    public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(
            new ResourceLocation(ExampleMod.MODID, "main"), () -> PROTOCOL_VERSION,
            PROTOCOL_VERSION::equals,
            PROTOCOL_VERSION::equals
    );

    private PacketHandler() {
    }

    public static void init() {
        int index = 0;
        INSTANCE.messageBuilder(ServerboundHammerThingAttackPacket.class, index++, NetworkDirection.PLAY_TO_SERVER)
                .encoder(ServerboundHammerThingAttackPacket::encode).decoder(ServerboundHammerThingAttackPacket::new)
                .consumerMainThread(ServerboundHammerThingAttackPacket::handle).add();
    }

}

(btw if you think the (first person) item animations are a bit awkward, I recommend you to look at this: https://forge.gemwire.uk/wiki/Custom_Item_Animations)

Edited by LeeCrafts
  • LeeCrafts changed the title to [1.19.4, SOLVED] Left-click charging mechanics for custom weapon

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

    • When I first heard about Bitcoin back in 2018, I was skeptical. The idea of a decentralized, digital currency seemed too good to be true. But I was intrigued as I learned more about the technology behind it and its potential. I started small, investing just a few hundred dollars, dipping my toes into the cryptocurrency waters. At first, it was exhilarating to watch the value of my investment grow exponentially. I felt like I was part of the future, an early adopter of this revolutionary new asset. But that euphoria was short-lived. One day, I logged into my digital wallet only to find it empty - my Bitcoin had vanished without a trace. It turned out that the online exchange I had trusted had been hacked, and my funds were stolen. I was devastated, both financially and emotionally. All the potential I had seen in Bitcoin was tainted by the harsh reality that with decentralization came a lack of regulation and oversight. My hard-earned money was gone, lost to the ether of the digital world. This experience taught me a painful lesson about the price of trust in the uncharted territory of cryptocurrency. While the technology holds incredible promise, the risks can be catastrophic if you don't approach it with extreme caution. My Bitcoin investment gamble had failed, and I was left to pick up the pieces, wiser but poorer for having placed my faith in the wrong hands. My sincere appreciation goes to MUYERN TRUST HACKER. You are my hero in recovering my lost funds. Send a direct m a i l ( muyerntrusted ( @ ) mail-me ( . )c o m ) or message on whats app : + 1 ( 4-4-0 ) ( 3 -3 -5 ) ( 0-2-0-5 )
    • You could try posting a log (if there is no log at all, it may be the launcher you are using, the FAQ may have info on how to enable the log) as described in the FAQ, however this will probably need to be reported to/remedied by the mod author.
    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
  • Topics

×
×
  • Create New...

Important Information

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