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

    • Hello! I have been having a problem with Forgematica, Embeddium, Oculus, and create. I wanted to download litematica so I could see which blocks are in my creative mode build, so that I could collect them all in survival. However, litematica is a fabric mod. I found a port called forgematica, which I added (along with it's dependency) to my mods folder. I loaded into a new world, and built a structure. Then, I added a part from the create mod, and the game crashed instantly, with exit code -1. Thanks for any help! Crash Report and mods list: https://pastebin.com/rtzh6LAi
    • To say that losing 40,000 BTC was a devastating blow would be an understatement. It was an emotional and financial crisis that left me feeling hopeless and utterly lost. For weeks, I was trapped in a whirlwind of regret, second-guessing every decision that led me to that point. The fear that I would never be able to recover such a significant sum of cryptocurrency consumed me, and with each passing day, my despair deepened. I had all but given up on ever regaining my wealth. Then I happened to stumble onto Tech Cyber Force Recovery. In the beginning, I was hesitant. It looked too good to be true: could someone get back so much of their lost Bitcoin? After trying several different approaches and programs without success, I was hesitant to put my trust in another recovery agency. However, I changed my mind after reading Tech Cyber Force Recovery's stellar reviews and reputation. Reaching out to their team was a risk I made. They were courteous and professional from the first time I got in touch with them. I felt like I wasn't just another case to be solved by the staff at Tech Cyber Force Recovery; they truly cared about getting me my lost Bitcoin back. They listened carefully to my circumstances and guided me through each stage, giving me succinct and understandable explanations as I went. Their passion gave me new hope, and their openness instantly made me feel better. As the recovery process began, I still had my doubts, but I knew I had placed my trust in the right hands. The Tech Cyber Force Recovery team kept me informed and updated on their progress, ensuring I never felt in the dark. Despite the complexity of my case, they worked tirelessly, and their expertise became evident at every turn. The level of professionalism and attention to detail they demonstrated throughout the process was beyond impressive. And then, after what felt like an eternity of anticipation, the moment I had been waiting for arrived. I received the news that my 40,000 BTC had been successfully recovered. It was hard to believe at first—it felt like a dream. The weight that had been dragging me down for so long was suddenly lifted, and I could breathe again. The financial loss I had feared would define my future was no longer a reality. I can’t fully express the emotions I felt during that moment. It was a mix of relief, joy, and an overwhelming sense of gratitude. I had gone from a place of utter despair to a complete resurgence of wealth, both emotionally and financially. The Tech Cyber Force Recovery team didn’t just restore my Bitcoin—they restored my faith in the possibility of recovery and gave me back something far more valuable: peace of mind. I will urge anyone in this same predicament to.  
    • Have you found a modder for this vehicle project? Because it will be really hard and I want to know that hero who can create all this
    • and what?????????
  • Topics

×
×
  • Create New...

Important Information

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