Search in sources :

Example 1 with BlockRayTraceResult

use of net.minecraft.util.math.BlockRayTraceResult in project Overloaded by CJ-MC-Mods.

the class ItemRayGun method handleMessage.

public void handleMessage(ServerPlayerEntity player, RayGunMessage message) {
    ItemStack itemStack = player.getItemInHand(Hand.MAIN_HAND);
    if (itemStack.getItem() != this) {
        return;
    }
    LazyOptional<IEnergyStorage> opEnergy = itemStack.getCapability(ENERGY);
    if (!opEnergy.isPresent()) {
        Overloaded.logger.warn("Railgun has no Energy Capability? NBT: " + itemStack.getTag());
        return;
    }
    IEnergyStorage energy = opEnergy.orElseThrow(() -> new RuntimeException("Impossible Condition"));
    if (energy.getEnergyStored() < OverloadedConfig.INSTANCE.rayGun.energyPerShot) {
        player.displayClientMessage(new StringTextComponent("Not enough power to fire."), true);
        return;
    }
    Vector3d eyePos = player.getEyePosition(1);
    if (eyePos.distanceTo(message.vector) > OverloadedConfig.INSTANCE.rayGun.maxRange) {
        player.displayClientMessage(new StringTextComponent("Target out of range."), true);
        return;
    }
    BlockRayTraceResult sanityCheckVec = player.level.clip(new RayTraceContext(eyePos, message.vector, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, player));
    if (sanityCheckVec.getType() != RayTraceResult.Type.MISS) {
        player.displayClientMessage(new StringTextComponent("Target no longer in sight."), true);
        return;
    }
    energy.extractEnergy(OverloadedConfig.INSTANCE.rayGun.energyPerShot, false);
    LightningBoltEntity entity = new LightningBoltEntity(EntityType.LIGHTNING_BOLT, player.level);
    entity.moveTo(message.vector.x, message.vector.y, message.vector.z, 0, 0);
    player.level.addFreshEntity(entity);
}
Also used : Vector3d(net.minecraft.util.math.vector.Vector3d) RayTraceContext(net.minecraft.util.math.RayTraceContext) LightningBoltEntity(net.minecraft.entity.effect.LightningBoltEntity) IEnergyStorage(net.minecraftforge.energy.IEnergyStorage) StringTextComponent(net.minecraft.util.text.StringTextComponent) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) ItemStack(net.minecraft.item.ItemStack)

Example 2 with BlockRayTraceResult

use of net.minecraft.util.math.BlockRayTraceResult in project Overloaded by CJ-MC-Mods.

the class RenderMultiToolAssist method renderWorldLastEvent.

@SubscribeEvent
public static void renderWorldLastEvent(RenderWorldLastEvent event) {
    float partialTick = Minecraft.getInstance().getFrameTime();
    PlayerEntity player = Minecraft.getInstance().player;
    if (player.getMainHandItem().getItem() != ModItems.multiTool)
        return;
    RayTraceResult resultPick = player.pick(OverloadedConfig.INSTANCE.multiToolConfig.reach, partialTick, false);
    if (resultPick.getType() == RayTraceResult.Type.MISS || !(resultPick instanceof BlockRayTraceResult)) {
        return;
    }
    BlockRayTraceResult result = ((BlockRayTraceResult) resultPick);
    ItemStack stack = ModItems.multiTool.getSelectedBlockItemStack(player.getMainHandItem());
    BlockState state;
    if (stack.getItem() instanceof BlockItem) {
        state = ((BlockItem) stack.getItem()).getBlock().defaultBlockState();
        state = state.getStateAtViewpoint(player.getCommandSenderWorld(), result.getBlockPos(), player.getEyePosition(partialTick));
        state = state.getBlock().getStateForPlacement(new BlockItemUseContextPublic(player.getCommandSenderWorld(), player, Hand.MAIN_HAND, stack, result));
    } else {
        state = Blocks.COBBLESTONE.defaultBlockState();
    }
    switch(getAssistMode()) {
        case PLACE_PREVIEW:
            if (!stack.isEmpty() && state != null)
                renderBlockPreview(event, result, state);
            break;
        case REMOVE_PREVIEW:
            renderRemovePreview(event, result);
            break;
        case BOTH_PREVIEW:
            renderRemovePreview(event, result);
            if (!stack.isEmpty() && state != null)
                renderBlockPreview(event, result, state);
    }
}
Also used : BlockState(net.minecraft.block.BlockState) RayTraceResult(net.minecraft.util.math.RayTraceResult) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) ItemStack(net.minecraft.item.ItemStack) BlockItem(net.minecraft.item.BlockItem) BlockItemUseContextPublic(com.cjm721.overloaded.util.BlockItemUseContextPublic) ClientPlayerEntity(net.minecraft.client.entity.player.ClientPlayerEntity) PlayerEntity(net.minecraft.entity.player.PlayerEntity) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent)

Example 3 with BlockRayTraceResult

use of net.minecraft.util.math.BlockRayTraceResult in project BluePower by Qmunity.

the class BPEventHandler method blockHighlightEvent.

@OnlyIn(Dist.CLIENT)
@SubscribeEvent
public void blockHighlightEvent(DrawHighlightEvent event) {
    PlayerEntity player = Minecraft.getInstance().player;
    if (player == null) {
        return;
    }
    World world = player.level;
    if (world == null) {
        return;
    }
    RayTraceResult mop = event.getTarget();
    if (mop instanceof BlockRayTraceResult) {
        BlockPos pos = ((BlockRayTraceResult) mop).getBlockPos();
        BlockState state = world.getBlockState(pos);
        if (state.getBlock() instanceof BlockBPMultipart) {
            BlockState partstate = MultipartUtils.getClosestState(player, pos);
            IVertexBuilder builder = event.getBuffers().getBuffer(RenderType.lines());
            if (partstate != null) {
                VoxelShape shape = partstate.getShape(world, pos, ISelectionContext.of(player));
                Vector3d projectedView = event.getInfo().getPosition();
                double d0 = pos.getX() - projectedView.x();
                double d1 = pos.getY() - projectedView.y();
                double d2 = pos.getZ() - projectedView.z();
                Matrix4f matrix4f = event.getMatrix().last().pose();
                shape.forAllEdges((startX, startY, startZ, endX, endY, endZ) -> {
                    builder.vertex(matrix4f, (float) (startX + d0), (float) (startY + d1), (float) (startZ + d2)).color(0.0F, 0.0F, 0.0F, 0.4F).endVertex();
                    builder.vertex(matrix4f, (float) (endX + d0), (float) (endY + d1), (float) (endZ + d2)).color(0.0F, 0.0F, 0.0F, 0.4F).endVertex();
                });
                event.setCanceled(true);
            }
        }
    }
}
Also used : Matrix4f(net.minecraft.util.math.vector.Matrix4f) BlockState(net.minecraft.block.BlockState) VoxelShape(net.minecraft.util.math.shapes.VoxelShape) Vector3d(net.minecraft.util.math.vector.Vector3d) RayTraceResult(net.minecraft.util.math.RayTraceResult) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) BlockBPMultipart(com.bluepowermod.block.BlockBPMultipart) BlockPos(net.minecraft.util.math.BlockPos) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) World(net.minecraft.world.World) PlayerEntity(net.minecraft.entity.player.PlayerEntity) IVertexBuilder(com.mojang.blaze3d.vertex.IVertexBuilder) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent) OnlyIn(net.minecraftforge.api.distmarker.OnlyIn)

Example 4 with BlockRayTraceResult

use of net.minecraft.util.math.BlockRayTraceResult in project BluePower by Qmunity.

the class TileDeployer method rightClick.

/**
 * Be sure to set up the fake player's hotbar with the right clicked items. starting with hotbar slot 0.
 * @param player
 * @param useItems this method will set the current selected slot of the fake player to 0, and move on to the next slot useItems - 1 times.
 *          So to use the first slot only, pass 1, to use the full hotbar, 9.
 * @return
 */
protected boolean rightClick(FakePlayer player, int useItems) {
    if (useItems > 9)
        throw new IllegalArgumentException("Hotbar is 9 items in width! You're trying " + useItems + "!");
    Direction faceDir = getFacingDirection();
    int dx = faceDir.getStepX();
    int dy = faceDir.getStepY();
    int dz = faceDir.getStepZ();
    int x = worldPosition.getX() + dx;
    int y = worldPosition.getY() + dy;
    int z = worldPosition.getZ() + dz;
    player.setPos(x + 0.5, y + 0.5 - player.getEyeHeight(), z + 0.5);
    player.xRot = faceDir.getStepY() * -90;
    switch(faceDir) {
        case NORTH:
            player.yRot = 180;
            break;
        case SOUTH:
            player.yRot = 0;
            break;
        case WEST:
            player.yRot = 90;
            break;
        case EAST:
            player.yRot = -90;
    }
    try {
        PlayerInteractEvent event = new PlayerInteractEvent.RightClickEmpty(player, Hand.MAIN_HAND);
        if (event.isCanceled())
            return false;
        Block block = level.getBlockState(new BlockPos(x, y, z)).getBlock();
        List<LivingEntity> detectedEntities = level.getEntitiesOfClass(LivingEntity.class, new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1));
        Entity entity = detectedEntities.isEmpty() ? null : detectedEntities.get(level.random.nextInt(detectedEntities.size()));
        if (entity != null) {
            for (int i = 0; i < useItems; i++) {
                player.inventory.selected = i;
                ItemStack stack = player.getMainHandItem();
                if (canDeployItem(stack) && stack.getItem().interactLivingEntity(stack, player, (LivingEntity) entity, Hand.MAIN_HAND).shouldSwing())
                    return true;
                if (entity instanceof AnimalEntity && ((AnimalEntity) entity).mobInteract(player, Hand.MAIN_HAND).shouldSwing())
                    return true;
            }
        }
        for (int i = 0; i < useItems; i++) {
            player.inventory.selected = i;
            ItemStack stack = player.getMainHandItem();
            if (canDeployItem(stack) && stack.getItem().onItemUseFirst(stack, new ItemUseContext(player, Hand.MAIN_HAND, new BlockRayTraceResult(new Vector3d(dx, dy, dz), faceDir, new BlockPos(x, y, z), false))) == ActionResultType.SUCCESS)
                return true;
        }
        for (int i = 0; i < useItems; i++) {
            player.inventory.selected = i;
            if (!level.isEmptyBlock(new BlockPos(x, y, z)) && block.use(level.getBlockState(new BlockPos(x, y, z)), level, new BlockPos(x, y, z), player, Hand.MAIN_HAND, new BlockRayTraceResult(new Vector3d(dx, dy, dz), faceDir, new BlockPos(x, y, z), false)) == ActionResultType.SUCCESS)
                return true;
        }
        for (int i = 0; i < useItems; i++) {
            player.inventory.selected = i;
            ItemStack stack = player.getMainHandItem();
            boolean isGoingToShift = false;
            if (!stack.isEmpty()) {
                if (stack.getItem() == Items.SUGAR_CANE || stack.getItem() == Items.REDSTONE) {
                    isGoingToShift = true;
                }
            }
            int useX = isGoingToShift ? worldPosition.getX() : x;
            int useY = isGoingToShift ? worldPosition.getY() : y;
            int useZ = isGoingToShift ? worldPosition.getZ() : z;
            if (canDeployItem(stack) && stack.getItem().useOn(new ItemUseContext(player, Hand.MAIN_HAND, new BlockRayTraceResult(new Vector3d(dx, dy, dz), faceDir, new BlockPos(x, y, z), false))) == ActionResultType.SUCCESS)
                return true;
        }
        for (int i = 0; i < useItems; i++) {
            player.inventory.selected = i;
            ItemStack stack = player.getMainHandItem();
            if (canDeployItem(stack)) {
                ItemStack copy = stack.copy();
                // TODO Check this
                player.setItemInHand(Hand.MAIN_HAND, stack.getItem().use(level, player, Hand.MAIN_HAND).getObject());
                if (!copy.sameItem(stack))
                    return true;
            }
        }
        return false;
    } catch (Throwable e) {
        BluePower.log.error("Deployer crashed! Stacktrace: ");
        e.printStackTrace();
        return true;
    }
}
Also used : AxisAlignedBB(net.minecraft.util.math.AxisAlignedBB) AnimalEntity(net.minecraft.entity.passive.AnimalEntity) Entity(net.minecraft.entity.Entity) PlayerEntity(net.minecraft.entity.player.PlayerEntity) LivingEntity(net.minecraft.entity.LivingEntity) ItemEntity(net.minecraft.entity.item.ItemEntity) ItemUseContext(net.minecraft.item.ItemUseContext) PlayerInteractEvent(net.minecraftforge.event.entity.player.PlayerInteractEvent) AnimalEntity(net.minecraft.entity.passive.AnimalEntity) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) Direction(net.minecraft.util.Direction) LivingEntity(net.minecraft.entity.LivingEntity) Vector3d(net.minecraft.util.math.vector.Vector3d) Block(net.minecraft.block.Block) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack)

Example 5 with BlockRayTraceResult

use of net.minecraft.util.math.BlockRayTraceResult in project Overloaded by CJ-MC-Mods.

the class PlayerInteractionUtil method placeBlock.

@Nonnull
public static BlockPlaceResult placeBlock(@Nonnull ItemStack searchStack, @Nonnull ServerPlayerEntity player, @Nonnull World worldIn, @Nonnull BlockPos newPosition, @Nonnull Direction facing, @Nonnull IEnergyStorage energy, float hitX, float hitY, float hitZ) {
    // Can we place a block at this Pos
    BlockItem itemBlock = ((BlockItem) searchStack.getItem());
    // if (worldIn.loadedAndEntityCanStandOn(newPosition, player)) {
    // return BlockPlaceResult.FAIL_DENY;
    // }
    BlockSnapshot blockSnapshot = BlockSnapshot.create(worldIn.dimension(), worldIn, newPosition);
    BlockState placedAgainst = blockSnapshot.getWorld().getBlockState(blockSnapshot.getPos().relative(facing.getOpposite()));
    BlockEvent.EntityPlaceEvent event = new BlockEvent.EntityPlaceEvent(blockSnapshot, placedAgainst, player);
    MinecraftForge.EVENT_BUS.post(event);
    if (event.isCanceled()) {
        return BlockPlaceResult.FAIL_DENY;
    }
    long distance = Math.round(Math.sqrt(player.blockPosition().distSqr(newPosition)));
    long cost = OverloadedConfig.INSTANCE.multiToolConfig.placeBaseCost + OverloadedConfig.INSTANCE.multiToolConfig.costPerMeterAway * distance;
    if (!player.abilities.instabuild && (cost > Integer.MAX_VALUE || cost < 0 || energy.getEnergyStored() < cost))
        return BlockPlaceResult.FAIL_ENERGY;
    LazyOptional<IItemHandler> opInventory = player.getCapability(ITEM_HANDLER_CAPABILITY, Direction.UP);
    if (!opInventory.isPresent()) {
        Overloaded.logger.warn("Player has no ItemHandler Capability? NBT: " + player.serializeNBT());
        return BlockPlaceResult.FAIL_PREREQUISITE;
    }
    IItemHandler inventory = opInventory.orElseThrow(() -> new RuntimeException("Impossible Condition"));
    int foundStackSlot = findItemStackSlot(searchStack, inventory);
    if (foundStackSlot == -1) {
        return BlockPlaceResult.FAIL_PREREQUISITE;
    }
    ItemStack foundStack = inventory.extractItem(foundStackSlot, 1, player.abilities.instabuild);
    BlockItemUseContext context = new BlockItemUseContextPublic(worldIn, player, Hand.MAIN_HAND, foundStack, new BlockRayTraceResult(new Vector3d(hitX + newPosition.getX(), hitY + newPosition.getY(), hitZ + newPosition.getZ()), facing, newPosition, false));
    ActionResultType result = ForgeHooks.onPlaceItemIntoWorld(context);
    switch(result) {
        case CONSUME:
        case SUCCESS:
            SoundType soundtype = worldIn.getBlockState(newPosition).getBlock().getSoundType(worldIn.getBlockState(newPosition), worldIn, newPosition, player);
            worldIn.playSound(null, newPosition, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F);
            if (!player.abilities.instabuild) {
                energy.extractEnergy((int) cost, false);
            }
            return BlockPlaceResult.SUCCESS;
        case PASS:
        case FAIL:
        default:
            inventory.insertItem(foundStackSlot, foundStack, player.abilities.instabuild);
            return BlockPlaceResult.FAIL_DENY;
    }
}
Also used : IItemHandler(net.minecraftforge.items.IItemHandler) ActionResultType(net.minecraft.util.ActionResultType) BlockSnapshot(net.minecraftforge.common.util.BlockSnapshot) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) BlockItem(net.minecraft.item.BlockItem) BlockItemUseContext(net.minecraft.item.BlockItemUseContext) Vector3d(net.minecraft.util.math.vector.Vector3d) ItemStack(net.minecraft.item.ItemStack) BlockEvent(net.minecraftforge.event.world.BlockEvent) Nonnull(javax.annotation.Nonnull)

Aggregations

BlockRayTraceResult (net.minecraft.util.math.BlockRayTraceResult)5 ItemStack (net.minecraft.item.ItemStack)4 Vector3d (net.minecraft.util.math.vector.Vector3d)4 PlayerEntity (net.minecraft.entity.player.PlayerEntity)3 BlockState (net.minecraft.block.BlockState)2 BlockItem (net.minecraft.item.BlockItem)2 BlockPos (net.minecraft.util.math.BlockPos)2 RayTraceResult (net.minecraft.util.math.RayTraceResult)2 SubscribeEvent (net.minecraftforge.eventbus.api.SubscribeEvent)2 BlockBPMultipart (com.bluepowermod.block.BlockBPMultipart)1 BlockItemUseContextPublic (com.cjm721.overloaded.util.BlockItemUseContextPublic)1 IVertexBuilder (com.mojang.blaze3d.vertex.IVertexBuilder)1 Nonnull (javax.annotation.Nonnull)1 Block (net.minecraft.block.Block)1 ClientPlayerEntity (net.minecraft.client.entity.player.ClientPlayerEntity)1 Entity (net.minecraft.entity.Entity)1 LivingEntity (net.minecraft.entity.LivingEntity)1 LightningBoltEntity (net.minecraft.entity.effect.LightningBoltEntity)1 ItemEntity (net.minecraft.entity.item.ItemEntity)1 AnimalEntity (net.minecraft.entity.passive.AnimalEntity)1