| 1 | package net.minecraft.world.item;
|
| 2 |
|
| 3 | import java.util.List;
|
| 4 | import java.util.Optional;
|
| 5 | import net.minecraft.core.BlockPos;
|
| 6 | import net.minecraft.tags.BlockTags;
|
| 7 | import net.minecraft.world.InteractionResult;
|
| 8 | import net.minecraft.world.entity.Leashable;
|
| 9 | import net.minecraft.world.entity.decoration.LeashFenceKnotEntity;
|
| 10 | import net.minecraft.world.entity.player.Player;
|
| 11 | import net.minecraft.world.item.context.UseOnContext;
|
| 12 | import net.minecraft.world.level.Level;
|
| 13 | import net.minecraft.world.level.block.state.BlockState;
|
| 14 | import net.minecraft.world.level.gameevent.GameEvent;
|
| 15 | import net.minecraft.world.phys.Vec3;
|
| 16 |
|
| 17 | public class LeadItem extends Item {
|
| 18 | public LeadItem(final Item.Properties properties) {
|
| 19 | super(properties);
|
| 20 | }
|
| 21 |
|
| 22 | @Override
|
| 23 | public InteractionResult useOn(final UseOnContext context) {
|
| 24 | Level level = context.getLevel();
|
| 25 | BlockPos pos = context.getClickedPos();
|
| 26 | BlockState state = level.getBlockState(pos);
|
| 27 | if (state.is(BlockTags.FENCES)) {
|
| 28 | Player player = context.getPlayer();
|
| 29 | if (!level.isClientSide() && player != null) {
|
| 30 | return bindPlayerMobs(player, level, pos);
|
| 31 | }
|
| 32 | }
|
| 33 |
|
| 34 | return InteractionResult.PASS;
|
| 35 | }
|
| 36 |
|
| 37 | public static InteractionResult bindPlayerMobs(final Player player, final Level level, final BlockPos pos) {
|
| 38 | List<Leashable> entitiesToLeash = Leashable.leashableInArea(level, Vec3.atCenterOf(pos), l -> l.getLeashHolder() == player);
|
| 39 | if (entitiesToLeash.isEmpty()) {
|
| 40 | return InteractionResult.PASS;
|
| 41 | }
|
| 42 |
|
| 43 | Optional<LeashFenceKnotEntity> existingKnot = LeashFenceKnotEntity.getKnot(level, pos);
|
| 44 | LeashFenceKnotEntity activeKnot = existingKnot.orElseGet(() -> LeashFenceKnotEntity.createKnot(level, pos));
|
| 45 | boolean anyLeashed = false;
|
| 46 |
|
| 47 | for (Leashable leashable : entitiesToLeash) {
|
| 48 | if (leashable.canHaveALeashAttachedTo(activeKnot)) {
|
| 49 | leashable.setLeashedTo(activeKnot, true);
|
| 50 | anyLeashed = true;
|
| 51 | }
|
| 52 | }
|
| 53 |
|
| 54 | if (anyLeashed) {
|
| 55 | activeKnot.playPlacementSound();
|
| 56 | level.gameEvent(GameEvent.BLOCK_ATTACH, pos, GameEvent.Context.of(player));
|
| 57 | return InteractionResult.SUCCESS_SERVER;
|
| 58 | }
|
| 59 |
|
| 60 | if (existingKnot.isEmpty()) {
|
| 61 | activeKnot.discard();
|
| 62 | }
|
| 63 |
|
| 64 | return InteractionResult.PASS;
|
| 65 | }
|
| 66 | }
|
| 67 |
|