Minecraft模组开发:如何通过代码在指定World和BlockPos位置放置方块
Minecraft双格高方块自动放置实现方案
核心逻辑
- 重写底部方块的放置触发方法,放置底部时自动检测上方可放置空间,生成对应上半部分方块
- 同步重写底部方块的移除触发方法,底部被破坏时同步销毁上方的上半部分方块,避免出现浮空残留
Forge 端实现代码
// 重写底部方块的onPlace方法 @Override public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { if (!level.isClientSide) { BlockPos upperPos = pos.above(); if (level.getBlockState(upperPos).canBeReplaced()) { // 替换为你自己注册的上半部分方块实例 level.setBlock(upperPos, YourModBlocks.UPPER_HALF_BLOCK.get().defaultBlockState(), 3); } } super.onPlace(state, level, pos, oldState, isMoving); } // 同步处理破坏逻辑 @Override public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) { if (!level.isClientSide) { BlockPos upperPos = pos.above(); if (level.getBlockState(upperPos).is(YourModBlocks.UPPER_HALF_BLOCK.get())) { level.removeBlock(upperPos, false); } } super.onRemove(state, level, pos, newState, isMoving); }
setBlock第三个参数3为更新标记组合,代表同时向客户端同步更新、阻止多余重渲染,是方块放置场景的常用配置。
Fabric 端实现代码
@Override public void onPlaced(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { if (!world.isClient) { BlockPos upperPos = pos.up(); if (world.getBlockState(upperPos).isReplaceable()) { // 替换为你自己注册的上半部分方块实例 world.setBlockState(upperPos, YourModBlocks.UPPER_HALF_BLOCK.getDefaultState(), Block.NOTIFY_ALL); } } super.onPlaced(world, pos, state, placer, itemStack); } @Override public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) { if (!world.isClient) { BlockPos upperPos = pos.up(); if (world.getBlockState(upperPos).isOf(YourModBlocks.UPPER_HALF_BLOCK)) { world.removeBlock(upperPos, false); } } super.onStateReplaced(state, world, pos, newState, moved); }
上半部分阴影问题修复方案
- 方块属性注册时添加
noOcclusion配置,关闭方块遮光判定,避免相邻方块投射阴影 - 方块模型JSON文件中添加配置
"ambientocclusion": false,关闭模型的环境光遮蔽计算,即可消除异常阴影
内容的提问来源于stack exchange,提问作者F4LS3
相关产品推荐
相关产品推荐

