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



×
×
  • Create New...

Important Information

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