|
| 1 | +package com.box3lab.item; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +import net.minecraft.server.level.ServerLevel; |
| 6 | +import net.minecraft.world.InteractionResult; |
| 7 | +import net.minecraft.world.entity.Display; |
| 8 | +import net.minecraft.world.entity.player.Player; |
| 9 | +import net.minecraft.world.item.Item; |
| 10 | +import net.minecraft.world.item.context.UseOnContext; |
| 11 | +import net.minecraft.world.level.Level; |
| 12 | +import net.minecraft.world.phys.AABB; |
| 13 | +import net.minecraft.world.phys.Vec3; |
| 14 | + |
| 15 | +public class ModelDestroyerItem extends Item { |
| 16 | + private static final double RANGE = 10.0; |
| 17 | + |
| 18 | + public ModelDestroyerItem(Properties properties) { |
| 19 | + super(properties); |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public InteractionResult useOn(UseOnContext context) { |
| 24 | + Level level = context.getLevel(); |
| 25 | + if (!(level instanceof ServerLevel serverLevel)) { |
| 26 | + return InteractionResult.SUCCESS; |
| 27 | + } |
| 28 | + |
| 29 | + Player player = context.getPlayer(); |
| 30 | + if (player == null) { |
| 31 | + return InteractionResult.PASS; |
| 32 | + } |
| 33 | + |
| 34 | + boolean deleted = deleteTarget(serverLevel, player); |
| 35 | + return deleted ? InteractionResult.SUCCESS : InteractionResult.PASS; |
| 36 | + } |
| 37 | + |
| 38 | + private static boolean deleteTarget(ServerLevel level, Player player) { |
| 39 | + Display.ItemDisplay target = findDisplay(level, player, RANGE); |
| 40 | + if (target == null) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + target.discard(); |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + private static Display.ItemDisplay findDisplay(ServerLevel level, Player player, double range) { |
| 48 | + Vec3 start = player.getEyePosition(1.0f); |
| 49 | + Vec3 look = player.getViewVector(1.0f); |
| 50 | + Vec3 end = start.add(look.scale(range)); |
| 51 | + AABB searchBox = player.getBoundingBox().expandTowards(look.scale(range)).inflate(1.5); |
| 52 | + |
| 53 | + List<Display.ItemDisplay> displays = level.getEntitiesOfClass(Display.ItemDisplay.class, searchBox); |
| 54 | + Display.ItemDisplay closest = null; |
| 55 | + double bestDist = range * range; |
| 56 | + |
| 57 | + for (Display.ItemDisplay display : displays) { |
| 58 | + AABB box = display.getBoundingBox().inflate(0.8); |
| 59 | + var hit = box.clip(start, end); |
| 60 | + if (hit.isEmpty()) { |
| 61 | + continue; |
| 62 | + } |
| 63 | + double dist = start.distanceToSqr(hit.get()); |
| 64 | + if (dist < bestDist) { |
| 65 | + bestDist = dist; |
| 66 | + closest = display; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return closest; |
| 71 | + } |
| 72 | +} |
0 commit comments