You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Forge 1.19.2模组开发:仿锂方块遇水移除背包物品求助

解决Minecraft 1.19.2 Forge模组中背包方块遇水消失的问题

核心实现方案

针对1.19.2版本特性,通过玩家Tick事件监听+背包物品遍历实现需求,同时适配版本特有的事件注册与物品操作逻辑。

具体代码实现

1. 注册玩家Tick事件

在模组事件处理类中注册PlayerTickEvent.Post事件(Post阶段确保玩家状态已更新):

public class ModEventHandlers {
    public static void register() {
        MinecraftForge.EVENT_BUS.addListener(ModEventHandlers::onPlayerTickPost);
    }

    private static void onPlayerTickPost(PlayerTickEvent.Post event) {
        Player player = event.getPlayer();
        // 跳过已死亡玩家,同时保证服务端与客户端同步执行
        if (!player.isAlive()) return;

        // 判断玩家是否处于水中(可根据需求添加淋雨判定)
        boolean isInWater = player.isInWater();

        if (isInWater) {
            // 遍历玩家背包所有物品槽
            for (int slot = 0; slot < player.getInventory().getContainerSize(); slot++) {
                ItemStack stack = player.getInventory().getItem(slot);
                // 匹配目标方块对应的物品实例
                if (stack.is(ModBlocks.YOUR_TARGET_BLOCK.get().asItem())) {
                    // 清空对应槽位的物品
                    player.getInventory().setItem(slot, ItemStack.EMPTY);
                    // 添加强化反馈(音效/粒子)
                    player.level.playSound(null, player.blockPosition(), SoundEvents.WET_GRASS, SoundSource.PLAYERS, 0.8F, 1.2F);
                }
            }
        }
    }
}

在模组主类的FMLCommonSetupEvent中触发事件注册:

@SubscribeEvent
public static void onCommonSetup(FMLCommonSetupEvent event) {
    ModEventHandlers.register();
}

2. 优化:避免重复处理

若不想每 Tick 都遍历背包,可通过玩家持久化数据添加状态标记,离开水后重置:

// 在onPlayerTickPost方法中添加
CompoundTag playerPersistentData = player.getPersistentData();
boolean hasProcessed = playerPersistentData.getBoolean("mod_water_processed");

if (isInWater) {
    if (!hasProcessed) {
        // 执行背包物品移除逻辑
        playerPersistentData.putBoolean("mod_water_processed", true);
    }
} else {
    if (hasProcessed) {
        playerPersistentData.putBoolean("mod_water_processed", false);
    }
}

常见问题排查

  • 事件未触发:确认使用MinecraftForge.EVENT_BUS注册事件,而非FMLJavaModLoadingContext.get().getModEventBus()(后者仅处理模组加载类事件)。
  • 物品匹配失败:必须用stack.is(目标物品实例)判断,不要直接用类比较,确保方块与物品实例关联正确。
  • 同步异常:服务端修改背包会自动同步到客户端,无需额外处理;若仅在客户端操作,会导致数据不一致,代码中不要跳过服务端逻辑。

模组开发能力提升建议

  • 直接参考Forge 1.19.2官方文档,重点研读事件系统、物品/方块API、玩家数据存储章节,版本对应文档的准确性远高于通用AI回答。
  • 下载Forge官方ExampleMod示例模组,拆解事件注册、物品逻辑的标准写法,模仿学习。
  • 加入Forge中文社区或官方Discord,针对版本特有问题直接咨询经验开发者。

内容的提问来源于stack exchange,提问作者Magne Lindholm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:10:09