This is an old revision of the document!
Table of Contents
添加一个物品
介绍
添加一个基本的物品是编写模组的第一步。 你将需要创建一个Item
对象,注册它,并赋予它一个材质。要向物品添加其他行为,你将需要一个自定义的Item
类。 在本教程以及以后的所有教程中,tutorial
(教程)名称空间均用作你模组的ID的占位符。(如果你有单独的模组ID,请一定使用它)
注册物品
首先,创建一个Item
对象。我们将其存放在模组主类的顶部。Item
的构造方法接受一个Item.Settings
对象,该对象用于设置物品属性,例如创造模式物品栏中的分类(物品组),耐久和堆叠数量。
public class ExampleMod implements ModInitializer { // 创建新物品对象 public static final Item FABRIC_ITEM = new Item(new Item.Settings().group(ItemGroup.MISC)); [...] }
这里使用原版注册方式来注册,基本语法是Registry#register(Registry Type, Identifier, Content)
,Registry Type参数指Registry类型中预定义的静态字段,Identifier指资源文件位置。Content则是您定义的实例(FABRIC_ITEM)。
public class ExampleMod implements ModInitializer { // 创建新物品的实例 public static final Item FABRIC_ITEM = new Item(new Item.Settings().group(ItemGroup.MISC)); @Override public void onInitialize() { } }
添加物品材质
为物品注册材质需要物品模型.json文件和材质图像文件。 您将需要将它们添加到资源目录中。每个的直接路径是:
物品模型: //<根目录>///resources/assets/tutorial/models/item/fabric_item.json 物品材质: //<根目录>///resources/assets/tutorial/textures/item/fabric_item.png
我们将使用这个示例材质。
如果您在第一步中正确注册了物品,则游戏将以类似于以下方式的方式抱怨缺少材质文件:
''[Server-Worker-1/WARN]: Unable to load model: 'tutorial:fabric_item#inventory' referenced from: tutorial:fabric_item#inventory: java.io.FileNotFoundException: tutorial:models/item/fabric_item.json''
游戏能很方便地告诉你它想要的资源路径。遇事不决,日志解决。
一个非常简单的模 A basic item model template is:
{ "parent": "item/generated", "textures": { "layer0": "tutorial:item/fabric_item" } }
物品的父项会更改其在手中的呈现方式,并且对库存中的冻结物品等有用。 “物品/手持”用于从纹理的左下角握住的工具。 textures / layer0是图像文件的位置。
最终纹理结果:
创建item类
要为物品添加功能/用处/特性,需要创建一个item类,其默认构造函数需要Item.Settings对象。
public class FabricItem extends Item { public FabricItem(Settings settings) { super(settings); } }
自定义Item类的一个实际用例是使该物品在您单击时播放声音:
public class FabricItem extends Item { public FabricItem(Settings settings) { super(settings); } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity playerEntity, Hand hand) { playerEntity.playSound(SoundEvents.BLOCK_WOOL_BREAK, 1.0F, 1.0F); return new TypedActionResult<>(ActionResult.SUCCESS, playerEntity.getStackInHand(hand)); } }
用新物品类的实例替换旧的Item对象:
public class ExampleMod implements ModInitializer { //创建新item的实例 public static final FabricItem FABRIC_ITEM = new FabricItem(new Item.Settings().group(ItemGroup.MISC)); [...] }
如果您正确执行了所有操作,则使用该物品现在应该会播放声音.
如果我想更改物品的堆叠大小怎么办?
使用maxCount(int size)来设置最大堆叠数。请注意,如果您的物品是有耐久的(及耐久归零后会被破坏),那么此物品无法设置最大堆叠数,否则游戏将抛出RuntimeException。
public class ExampleMod implements ModInitializer { //我们新物品的实例,最大堆叠大小为16 public static final FabricItem FABRIC_ITEM = new FabricItem(new Item.Settings().group(ItemGroup.MISC).maxCount(16)); [...] }