Flandre923
364 words
2 minutes
14 如何注册一个按键

14 如何注册一个按键#


/**
 * 注册到游戏中的事件总线,仅在客户端有效。
 */
@EventBusSubscriber(modid = NeoMafishMod.MODID, value = Dist.CLIENT, bus = EventBusSubscriber.Bus.GAME)
@OnlyIn(Dist.CLIENT)
public class KeyInputHandler {

    /**
     * 定义按键分类和特定按键的资源路径。
     */
    public static final String KEY_CATEGORY_TUTORIAL = "key.category.mafishmod.tutorial";
    public static final String KEY_THROW_ITEM = "key.mafishmod.throw_item";

    /**
     * 定义一个按键映射,用于绑定到特定的键盘按键上。
     */
    public static KeyMapping throwingKey = new KeyMapping(
            KEY_THROW_ITEM,
            KeyConflictContext.IN_GAME,
            InputConstants.Type.KEYSYM,
            GLFW.GLFW_KEY_Y,
            KEY_CATEGORY_TUTORIAL
    );

    // 投掷力度相关字段
    private static float throwPower = 0.0f;
    private static boolean isCharging = false;
    private static final float maxThrowPower = 2.0f; // 定义最大投掷力度
    private static long chargeStartTime = 0;
    private static long chargeEndTime = 0;

    /**
     * 在每个客户端tick事件后调用,用于处理按键输入并累计投掷力度。
     * @param event 客户端tick事件对象
     */
    @SubscribeEvent
    public static void registerKeyInputs(ClientTickEvent.Post event) {
        var client = Minecraft.getInstance();
        if (throwingKey.isDown()) {
            // 按键被按下时的处理逻辑

            if (!isCharging)
            {
                chargeStartTime = System.currentTimeMillis();
                isCharging = true;
            }
            else
            {
                chargeEndTime = System.currentTimeMillis();
                long chargeDuration = chargeEndTime - chargeStartTime;

                throwPower = Math.min((float) (chargeDuration/1000.0),maxThrowPower);
                client.player.displayClientMessage(Component.literal("蓄力: "+throwPower),true);

            }
        } else if (isCharging) {
            // 按键被释放时的处理逻辑

            chargeEndTime = System.currentTimeMillis();
            long chargeDuration = chargeEndTime - chargeStartTime;
            throwPower = Math.min((float)(chargeDuration / 1000.0),maxThrowPower);
            client.player.displayClientMessage(Component.literal("重置为0"),true);
            throwPower = 0.0f;
            isCharging = false;
            chargeStartTime = 0;
            chargeEndTime = 0;
        }
    }

    /**
     * 静态内部类,用于注册按键映射事件。
     */
    public static class KeyRegistries {
        @SubscribeEvent
        public static void register(RegisterKeyMappingsEvent event) {
            event.register(KeyInputHandler.throwingKey);
        }
    }

    /**
     * 获取当前的投掷力度。
     * @return 当前的投掷力度值
     */
    public static float getThrowPower() {
        return throwPower;
    }
}

14 如何注册一个按键
https://fuwari.vercel.app/posts/minecraft1_21_0/14__如何注册一个按键/
Author
Flandre923
Published at
2024-08-24