| 1 | package net.minecraft.world.item;
|
| 2 |
|
| 3 | import net.minecraft.core.BlockPos;
|
| 4 | import net.minecraft.server.level.ServerLevel;
|
| 5 | import net.minecraft.tags.BlockTags;
|
| 6 | import net.minecraft.world.InteractionResult;
|
| 7 | import net.minecraft.world.entity.Entity;
|
| 8 | import net.minecraft.world.entity.EntitySpawnReason;
|
| 9 | import net.minecraft.world.entity.EntityType;
|
| 10 | import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
| 11 | import net.minecraft.world.item.context.UseOnContext;
|
| 12 | import net.minecraft.world.level.Level;
|
| 13 | import net.minecraft.world.level.block.BaseRailBlock;
|
| 14 | import net.minecraft.world.level.block.state.BlockState;
|
| 15 | import net.minecraft.world.level.block.state.properties.RailShape;
|
| 16 | import net.minecraft.world.level.gameevent.GameEvent;
|
| 17 | import net.minecraft.world.phys.Vec3;
|
| 18 |
|
| 19 | public class MinecartItem extends Item {
|
| 20 | private final EntityType<? extends AbstractMinecart> type;
|
| 21 |
|
| 22 | public MinecartItem(final EntityType<? extends AbstractMinecart> type, final Item.Properties properties) {
|
| 23 | super(properties);
|
| 24 | this.type = type;
|
| 25 | }
|
| 26 |
|
| 27 | @Override
|
| 28 | public InteractionResult useOn(final UseOnContext context) {
|
| 29 | Level level = context.getLevel();
|
| 30 | BlockPos pos = context.getClickedPos();
|
| 31 | BlockState blockState = level.getBlockState(pos);
|
| 32 | if (!blockState.is(BlockTags.RAILS)) {
|
| 33 | return InteractionResult.FAIL;
|
| 34 | }
|
| 35 |
|
| 36 | ItemStack itemStack = context.getItemInHand();
|
| 37 | RailShape shape = blockState.getBlock() instanceof BaseRailBlock
|
| 38 | ? blockState.getValue(((BaseRailBlock)blockState.getBlock()).getShapeProperty())
|
| 39 | : RailShape.NORTH_SOUTH;
|
| 40 | double offset = 0.0;
|
| 41 | if (shape.isSlope()) {
|
| 42 | offset = 0.5;
|
| 43 | }
|
| 44 |
|
| 45 | Vec3 spawnPos = new Vec3(pos.getX() + 0.5, pos.getY() + 0.0625 + offset, pos.getZ() + 0.5);
|
| 46 | AbstractMinecart cart = AbstractMinecart.createMinecart(
|
| 47 | level, spawnPos.x, spawnPos.y, spawnPos.z, this.type, EntitySpawnReason.DISPENSER, itemStack, context.getPlayer()
|
| 48 | );
|
| 49 | if (cart == null) {
|
| 50 | return InteractionResult.FAIL;
|
| 51 | }
|
| 52 |
|
| 53 | if (AbstractMinecart.useExperimentalMovement(level)) {
|
| 54 | for (Entity entity : level.getEntities(null, cart.getBoundingBox())) {
|
| 55 | if (entity instanceof AbstractMinecart) {
|
| 56 | return InteractionResult.FAIL;
|
| 57 | }
|
| 58 | }
|
| 59 | }
|
| 60 |
|
| 61 | if (level instanceof ServerLevel serverLevel) {
|
| 62 | serverLevel.addFreshEntity(cart);
|
| 63 | serverLevel.gameEvent(GameEvent.ENTITY_PLACE, pos, GameEvent.Context.of(context.getPlayer(), serverLevel.getBlockState(pos.below())));
|
| 64 | }
|
| 65 |
|
| 66 | itemStack.shrink(1);
|
| 67 | return InteractionResult.SUCCESS;
|
| 68 | }
|
| 69 | }
|
| 70 |
|