Thought this might be useful to someone out there. Sure helped me a lot, Now i dont have to do these with loot tables.
import { world, ItemStack, GameMode } from "@minecraft/server";
const FORTUNE_DROPS = {
"example:block_type": "example:drop_item",
};
function calcCountFromFortune(level) {
return level === 0 ? 1 : (1 + Math.floor(Math.random() * (level + 1)));
}
world.afterEvents.playerBreakBlock.subscribe((ev) => {
try {
const preId = ev.brokenBlockPermutation?.type?.id;
const dropTypeId = preId && FORTUNE_DROPS[preId];
if (!dropTypeId) return;
if (ev.player.getGameMode() === GameMode.Creative) return;
const tool = ev.itemStackBeforeBreak ?? ev.itemStackAfterBreak;
if (!tool) return;
const ench = tool.getComponent("minecraft:enchantable");
const silk = ench?.getEnchantment("silk_touch")?.level ?? 0;
if (silk > 0) return;
const fortune = ench?.getEnchantment("fortune")?.level ?? 0;
const count = calcCountFromFortune(fortune);
const stack = new ItemStack(dropTypeId, count);
ev.dimension.spawnItem(stack, ev.block.location);
} catch (e) {
console.warn(`[fortune] ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
}
});