跳到主要内容

7高级方块

定义声音块

我们定义一个物品块只要去继承Block,然后可以重写一些方法

/**
* @author houyunfei
*/
public class SoundBlock extends Block {

public SoundBlock(Settings settings) {
super(settings);
}

@Override
protected ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) {
world.playSound(player, pos, SoundEvents.BLOCK_NOTE_BLOCK_XYLOPHONE.value(), SoundCategory.BLOCKS, 1.0F, 1.0F);
return ActionResult.SUCCESS;
}
}

注册声音块

在ModBlocks中进行注册:

public static final Block SOUND_BLOCK =registerBlock("sound_block", new SoundBlock(FabricBlockSettings.copyOf(Blocks.IRON_BLOCK)));

然后在ModItemGroups中把块加入到物品组中:

entries.add(ModBlocks.SOUND_BLOCK)

测试效果

此时将方块放在地上点击会有声音

image-20240823191737627