多BlockState方块
Minecraft有普通的木箱子,为什么就没有铁箱子呢?这一节,笔者将以铁箱子为例,带领读者创建多BlockState方块。
BlockState
是Minecraft 1.8引入的系统,用以替代原先标记方块状态使用的Metadata
。顾名思义,BlockState
就是方块状态,如熔炉的不同的朝向、红石灯的亮灭等。
Block
与BlockState
,就好比Item
与ItemStack
。Minecraft中世界的方块,就是以BlockState
存储的。BlockState
与Block
相比,多了xyz的坐标信息,还多了state
信息。也就是上文所述的熔炉、红石灯不同的状态。
开始创建方块
首先就是方块的类,创建类的方法与3.2.6章节的相似,这里就不重复说了。
src/main/java/xyz/bzstudio/modderguide/block/IronChest.java(部分)
:
public class IronChest extends Block {
public IronChest() {
super(Properties.create(Material.IRON));
}
}
然后,就是添加state
的阶段。state
在代码中叫Property
,在方块的类中创建以下常量。
public static final DirectionProperty FACING = HorizontalBlock.HORIZONTAL_FACING;
DirectionProperty
指的是朝向,如果该state是布尔值 (例如红石灯的亮与灭) ,则是BooleanProperty
。如果有更复杂的需求,则需要自行创建相应的Enum。
我们已经创建了方块状态,但现在游戏并不认得我们的方块状态,我们需要覆写fillStateContainer()
方法,向方块中添加这个state。
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
builder.add(<your_states>);
}
同时,我们还要设置默认的BlockState。
public MetalChest() {
super(Properties.create(Material.IRON));
this.setDefaultState(this.stateContainer.getBaseState().with(FACING, Direction.NORTH));
}
由于我们设置了有关方块朝向的state,所以我们还要覆写下面的方法。
public BlockState rotate(BlockState state, Rotation rot) {
return state.with(FACING, rot.rotate(state.get(FACING)));
}
public BlockState mirror(BlockState state, Mirror mirrorIn) {
return state.rotate(mirrorIn.toRotation(state.get(FACING)));
}
但当我们无论朝向哪儿放置方块时,Minecraft默认放置的是刚刚设置的DefaultState。这显然与我们的目的不符。因为我们没有覆写getStateForPlacement()
方法。
public BlockState getStateForPlacement(BlockItemUseContext context) {
return this.getDefaultState().with(FACING, context.getPlacementHorizontalFacing().getOpposite());
}
模型与材质
至此,我们方块的基础部分就完成了,接下来就是模型与材质。
首先就是blockstate的json文件。
src/main/resources/assets/modderguide/blockstates/iron_chest.json
:
{
"variants": {
// 表明当facing为north时,模型为modderguide:block/iron_chest。
// 如果有其它state,那么这里的facing与其它state需要按字母表排序。
"facing=north": { "model": "modderguide:block/iron_chest" },
"facing=south": { "model": "modderguide:block/iron_chest", "y": 180 },
"facing=west": { "model": "modderguide:block/iron_chest", "y": 270 },
"facing=east": { "model": "modderguide:block/iron_chest", "y": 90 }
}
}
对应的模型、材质等自然不用多说。