Item Event Migration
help
开始之前
本页面要求您熟悉基础的JavaScript知识,并了解现代物品事件的工作原理。
在将物品的JSON事件升级为自定义组件时遇到困难?别担心!本页面将帮助您理解如何使用脚本API实现那些已弃用的JSON事件响应。
添加生物效果
自定义组件
js
onHitEntity({ hitEntity }) {
hitEntity.addEffect("regeneration", 30, {
amplifier: 10,
showParticles: false
});
}伤害(持有者)
js
import { EntityDamageCause } from "@minecraft/server";自定义组件
js
onUse({ source }) {
source.applyDamage(2, {
cause: EntityDamageCause.drowning
});
}伤害(物品)
js
import { EquipmentSlot, GameMode, Player } from "@minecraft/server";自定义组件
js
onMineBlock({ source }) {
// 获取主手槽位
if (!(source instanceof Player)) return;
const equippable = source.getComponent("minecraft:equippable");
if (!equippable) return;
const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
if (!mainhand.hasItem()) return;
// 非创造模式下应用耐久度伤害
if (source.getGameMode() === GameMode.creative) return;
const itemStack = mainhand.getItem(); // 允许我们获取物品组件
const durability = itemStack.getComponent("minecraft:durability");
if (!durability) return;
// 考虑耐久附魔
const enchantable = itemStack.getComponent("minecraft:enchantable");
const unbreakingLevel = enchantable?.getEnchantment("unbreaking")?.level;
const damageChance = durability.getDamageChance(unbreakingLevel) / 100;
if (Math.random() > damageChance) return; // 根据耐久等级随机跳过伤害
// 对物品造成伤害
const shouldBreak = durability.damage === durability.maxDurability;
if (shouldBreak) {
mainhand.setItem(undefined); // 移除物品
source.playSound("random.break"); // 播放破坏音效
} else {
durability.damage++; // 增加耐久度伤害
mainhand.setItem(itemStack); // 更新主手中的物品
}
}减少堆叠数量
js
import { EquipmentSlot, GameMode } from "@minecraft/server";自定义组件
js
onUse({ source }) {
if (!source) return;
const equippable = source.getComponent("minecraft:equippable");
if (!equippable) return;
const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
if (!mainhand.hasItem()) return;
if (source.getGameMode() !== GameMode.creative) {
if (mainhand.amount > 1) {
mainhand.amount--; // 从堆叠中移除一个物品
} else {
mainhand.setItem(undefined); // 移除整个物品堆叠
}
}
}移除生物效果
自定义组件
js
onHitEntity({ hitEntity }) {
hitEntity.removeEffect("regeneration");
}执行命令
自定义组件
js
onUse({ source }) {
source.runCommand("say Hello there!")
source.runCommand("say Welcome to my world!")
}传送
自定义组件
js
onConsume({ source }) {
source.teleport({ x: 100, y: 20, z: 786 });
}转换物品
js
import { EquipmentSlot, ItemStack } from "@minecraft/server";自定义组件
js
onUse({ source }) {
const equippable = source?.getComponent("minecraft:equippable");
if (!equippable) return;
const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
mainhand.setItem(new ItemStack("minecraft:suspicious_stew"));
}贡献者
编辑 Item Event Migration本页面上的文本和图像内容根据 知识共享署名 4.0 国际许可协议
本页中的代码示例根据 MIT 许可证
