Unicopia/src/main/java/com/minelittlepony/unicopia/item/SpellbookItem.java

91 lines
2.5 KiB
Java
Raw Normal View History

2021-11-09 17:29:55 +01:00
package com.minelittlepony.unicopia.item;
import org.jetbrains.annotations.Nullable;
import com.minelittlepony.unicopia.entity.SpellbookEntity;
import com.minelittlepony.unicopia.entity.UEntities;
import com.minelittlepony.unicopia.util.Dispensable;
import net.minecraft.block.DispenserBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BookItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.nbt.NbtCompound;
2021-11-09 17:29:55 +01:00
import net.minecraft.util.ActionResult;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.BlockPointer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
public class SpellbookItem extends BookItem implements Dispensable {
public SpellbookItem(Settings settings) {
super(settings);
DispenserBlock.registerBehavior(this, createDispenserBehaviour());
}
@Override
public TypedActionResult<ItemStack> dispenseStack(BlockPointer source, ItemStack stack) {
Direction facing = source.getBlockState().get(DispenserBlock.FACING);
2021-12-22 10:15:09 +01:00
BlockPos pos = source.getPos().offset(facing);
2021-11-09 17:29:55 +01:00
float yaw = facing.getOpposite().asRotation();
placeBook(stack, source.getWorld(), pos.getX(), pos.getY(), pos.getZ(), yaw);
2021-11-09 17:29:55 +01:00
stack.decrement(1);
return new TypedActionResult<>(ActionResult.SUCCESS, stack);
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
@Nullable
PlayerEntity player = context.getPlayer();
2022-09-21 22:58:29 +02:00
if (!context.getWorld().isClient) {
2021-11-09 17:29:55 +01:00
BlockPos pos = context.getBlockPos().offset(context.getSide());
placeBook(context.getStack(), context.getWorld(), pos.getX(), pos.getY(), pos.getZ(), context.getPlayerYaw() + 180);
2021-11-09 17:29:55 +01:00
if (!player.getAbilities().creativeMode) {
player.getStackInHand(context.getHand()).decrement(1);
}
return ActionResult.SUCCESS;
}
return ActionResult.PASS;
}
private static void placeBook(ItemStack stack, World world, int x, int y, int z, float yaw) {
2021-11-09 17:29:55 +01:00
SpellbookEntity book = UEntities.SPELLBOOK.create(world);
book.refreshPositionAndAngles(x + 0.5, y, z + 0.5, 0, 0);
book.setHeadYaw(yaw);
book.setYaw(yaw);
@Nullable
NbtCompound tag = stack.getSubNbt("spellbookState");
if (tag != null) {
book.getSpellbookState().fromNBT(tag);
}
2021-11-09 17:29:55 +01:00
world.spawnEntity(book);
}
}