Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 160
src/main/java/com/kodari/lightningrod/LightningRodMod.java
package com.kodari.lightningrod;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.player.UseEntityCallback;
import net.minecraft.component.DataComponentTypes;
import net.minecraft.component.type.NbtComponent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LightningEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.ActionResult;
import net.minecraft.world.World;
public class LightningRodMod implements ModInitializer {
private static final String MARKER_KEY = "lightningrod";
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) ->
dispatcher.register(CommandManager.literal("lightningrod").executes(context -> {
ServerPlayerEntity player = context.getSource().getPlayerOrThrow();
ItemStack rod = new ItemStack(Items.FISHING_ROD);
NbtCompound customData = new NbtCompound();
customData.putBoolean(MARKER_KEY, true);
rod.set(DataComponentTypes.CUSTOM_DATA, NbtComponent.of(customData));
player.giveOrDropStack(rod);
return 1;
})));
UseEntityCallback.EVENT.register((player, world, hand, entity, hitResult) -> {
ItemStack stack = player.getStackInHand(hand);
if (!isLightningRod(stack)) {
return ActionResult.PASS;
}
if (world.isClient()) {
return ActionResult.SUCCESS;
}
if (!(world instanceof ServerWorld serverWorld) || !(player instanceof ServerPlayerEntity serverPlayer)) {
return ActionResult.FAIL;
}
if (serverPlayer.getItemCooldownManager().isCoolingDown(stack)) {
return ActionResult.FAIL;
}
LightningEntity lightning = new LightningEntity(EntityType.LIGHTNING_BOLT, serverWorld);
lightning.setCosmetic(true);
lightning.setPosition(entity.getX(), entity.getY(), entity.getZ());
serverWorld.spawnEntity(lightning);
entity.damage(serverWorld, entity.getDamageSources().lightningBolt(), 20.0F);
serverPlayer.getItemCooldownManager().set(stack, 600);
return ActionResult.SUCCESS;
});
}
private static boolean isLightningRod(ItemStack stack) {
NbtComponent customData = stack.get(DataComponentTypes.CUSTOM_DATA);
return customData != null && customData.copyNbt().getBoolean(MARKER_KEY, false);
}
}