自定义食物
easy
scripting
格式版本 1.21.70
本教程需要您具备自定义物品的基础知识。 开始前请先阅读物品指南!
本文将指导您创建食用后能为玩家附加效果的自定义食物(类似金苹果机制)。
基础物品JSON
BP/items/custom_food.json
json
{
"format_version": "1.21.70",
"minecraft:item": {
"description": {
"identifier": "wiki:custom_food",
"menu_category": {
"category": "equipment",
"group": "minecraft:itemGroup.name.miscFood"
}
},
"components": {
"minecraft:icon": "wiki:custom_food",
"minecraft:food": {
"nutrition": 4,
"saturation_modifier": 0.6
},
"minecraft:use_animation": "eat",
"minecraft:use_modifiers": {
"use_duration": 1.6,
"movement_modifier": 0.33
},
"minecraft:tags": {
"tags": [
"minecraft:is_food",
"minecraft:is_meat", // 仅当食物属于肉类时添加
"minecraft:is_cooked" // 仅当食物是熟食时添加
]
}
}
}
}如果您已了解如何正确放置纹理文件,可以直接跳过此部分。但请注意,仅将纹理文件放入RP/textures/items文件夹是不够的。
我们需要在资源包的RP/textures/item_texture.json文件中创建名为wiki:custom_<物品>的对象,如下例所示。
RP/textures/item_texture.json
json
{
"texture_name": "atlas.items",
"texture_data": {
"wiki:custom_food": {
"textures": "textures/items/custom_food"
}
}
}附加效果实现
要实现食物食用时附加效果的功能,我们需要使用自定义组件。
本教程中我们将创建名为wiki:food_effects的自定义组件,请确保将命名空间修改为您的附加包专属标识。
minecraft:item > components
json
"minecraft:custom_components": ["wiki:food_effects"]自定义组件脚本
在脚本文件中,只需监听特定物品使用事件,当玩家食用该物品后即可获得一个或多个效果,代码如下:
BP/scripts/main.js
js
import { world } from "@minecraft/server";
const ItemFoodEffectsComponent = {
onConsume({ itemStack, source }) {
// 检测触发效果的物品
if (itemStack.typeId === "wiki:custom_food") {
// minecraft:speed 是效果名称
// 100 是效果持续时间(单位:游戏刻,20刻=1秒)
source.addEffect("minecraft:speed", 100, {
amplifier: 2, // 效果等级(1-256)
showParticle: true, // 是否显示粒子效果
});
}
},
};
world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
// 注册自定义组件以供物品JSON调用
itemComponentRegistry.registerCustomComponent("wiki:food_effects", ItemFoodEffectsComponent);
});贡献者
编辑 自定义食物本页面上的文本和图像内容根据 知识共享署名 4.0 国际许可协议
本页中的代码示例根据 MIT 许可证

