本篇教程的视频

本篇教程的源代码

GitHub地址:TutorialMod-Pillar-1.20.1

本篇教程目标

  • 学会制作可连接方块的变种,判断竖向

柱类方块类

这里我们直接来写这个柱类方块,因为我们之前已经写过一个可连接方块了,而这一次写的柱子要比之前的沙发还要简单

之前的沙发判断的是左右,而这一次,我们只要判断上下的方位就好了

PillarBlock

创建PillarBlock类,继承自Block

1
2
3
4
5
public class PillarBlock extends Block {
public PillarBlock(Settings settings) {
super(settings);
}
}

方块属性

同样的,我们来写一个方块属性的枚举类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public enum Type implements StringIdentifiable{
SINGLE("single"),
TOP("top"),
BOTTOM("bottom"),
MIDDLE("middle");

private final String id;

Type(String id) {
this.id = id;
}

@Override
public String asString() {
return this.id;
}
}

同样还是实现StringIdentifiable这个接口,然后按照之前的写法来写4个不同的状态

声明方块属性

1
public static final EnumProperty<Type> TYPE = EnumProperty.of("type2", Type.class);

因为我们之前已经注册了一个EnumProperty类型的type,所以这里的注册id要改一下

然后进行方块属性的初始化

1
this.setDefaultState(this.getStateManager().getDefaultState().with(TYPE, Type.SINGLE));

那么默认就是SINGLE这个状态

还要将方块属性加入到方块中

1
2
3
4
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(TYPE);
}

重写方法

最后我们就要重写方法,改变方块的方块状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
public BlockState getStateForNeighborUpdate(BlockState state, Direction direction, BlockState neighborState, WorldAccess world, BlockPos pos, BlockPos neighborPos) {
boolean top = world.getBlockState(pos.up()).isOf(this);
boolean bottom = world.getBlockState(pos.down()).isOf(this);
if (top && bottom) {
return state.with(TYPE, Type.MIDDLE);
} else if (top) {
return state.with(TYPE, Type.BOTTOM);
} else if (bottom) {
return state.with(TYPE, Type.TOP);
} else {
return state.with(TYPE, Type.SINGLE);
}
}

这里我们要重写getStateForNeighborUpdate方法

两个布尔值分别判断当前方块的上下是否为相同的方块,然后根据这两个布尔值来设置不同的方块状态

好了,这个方块类就这样写完了

其实方块状态能玩出很多花活来,你可以用方块状态来实现很多各种各样的方块,
即便你现在不是很熟练,写得多了,自然就会了

注册方块

注册

注册方块和之前一样,直接注册即可

1
2
public static final Block PILLAR = register("pillar",
new PillarBlock(AbstractBlock.Settings.create().strength(2.0f, 6.0f).nonOpaque()));

实例化PillarBlock,同样,因为这个是Blockbench制作的非实心方块,所以这里要设置nonOpaque()

物品栏

同样的,我们也要注册物品栏

1
entries.add(ModBlocks.PILLAR);

数据文件

语言文件

1
translationBuilder.add(ModBlocks.PILLAR, "Pillar");

模型文件

1
blockStateModelGenerator.registerParentedItemModel(ModBlocks.PILLAR, ModelIds.getBlockModelId(ModBlocks.PILLAR));

方块状态呢,你可以按照之前我们写沙发那样来写,不过我这里就直接自己写了,只让它生成一个方块物品的模型文件就好了

registerParentedItemModel方法就是生成一个与方块同名的物品模型文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"variants": {
"type2=single": {
"model": "tutorial-mod:block/pillar"
},
"type2=top": {
"model": "tutorial-mod:block/pillar_top"
},
"type2=bottom": {
"model": "tutorial-mod:block/pillar_bottom"
},
"type2=middle": {
"model": "tutorial-mod:block/pillar_middle"
}
}
}

这个是方块状态文件

测试

那么最后我们就可以进入游戏进行测试了