Jump to content

How to Get the Entity the Player is Looking At 1.19.3


Noxxous

Recommended Posts


import java.util.function.Predicate;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.VoxelShape;

public class RayTrace implements BlockGetter {
    private static Predicate<Entity> isVisible =
            entity -> !entity.isSpectator() && entity.isPickable();
    private static Minecraft minecraft = Minecraft.getInstance();

    @Override
    public BlockEntity getBlockEntity(BlockPos pos) {
        return minecraft.level.getBlockEntity(pos);
    }

    @Override
    public BlockState getBlockState(BlockPos pos) {
        return minecraft.level.getBlockState(pos);
    }

    @Override
    public FluidState getFluidState(BlockPos pos) {
        return minecraft.level.getFluidState(pos);
    }

    public LivingEntity getEntityInCrosshair(float partialTicks, double reachDistance) {
        Minecraft client = Minecraft.getInstance();
        Entity viewer = client.getCameraEntity();

        if (viewer == null) {
            return null;
        }

        Vec3 position = viewer.getEyePosition(partialTicks);
        Vec3 look = viewer.getViewVector(1.0F);
        Vec3 max = position.add(look.x * reachDistance, look.y * reachDistance, look.z * reachDistance);
        AABB searchBox =
                viewer.getBoundingBox().expandTowards(look.scale(reachDistance)).inflate(1.0D, 1.0D, 1.0D);

        EntityHitResult result = ProjectileUtil.getEntityHitResult(viewer, position, max, searchBox,
                isVisible, reachDistance * reachDistance);

        if (result == null || result.getEntity() == null) {
            return null;
        }

        if (result.getEntity() instanceof LivingEntity) {
            LivingEntity target = (LivingEntity) result.getEntity();

            HitResult blockHit =
                    clip(setupRayTraceContext(client.player, reachDistance, ClipContext.Fluid.NONE));

            if (!blockHit.getType().equals(BlockHitResult.Type.MISS)) {
                double blockDistance = blockHit.getLocation().distanceTo(position);
                if (blockDistance > target.distanceTo(client.player)) {
                    return target;
                }
            } else {
                return target;
            }
        }

        return null;
    }

    private ClipContext setupRayTraceContext(Player player, double distance, ClipContext.Fluid fluidHandling) {
        float pitch = player.getXRot();
        float yaw = player.getYRot();
        Vec3 fromPos = player.getEyePosition(1.0F);
        float float_3 = Mth.cos(-yaw * 0.017453292F - 3.1415927F);
        float float_4 = Mth.sin(-yaw * 0.017453292F - 3.1415927F);
        float float_5 = -Mth.cos(-pitch * 0.017453292F);
        float xComponent = float_4 * float_5;
        float yComponent = Mth.sin(-pitch * 0.017453292F);
        float zComponent = float_3 * float_5;
        Vec3 toPos = fromPos.add((double) xComponent * distance, (double) yComponent * distance,
                (double) zComponent * distance);
        return new ClipContext(fromPos, toPos, ClipContext.Block.OUTLINE, fluidHandling, player);
    }

    @Override
    public BlockHitResult clip(ClipContext context) {
        return BlockGetter.traverseBlocks(context.getFrom(), context.getTo(), context, (c, pos) -> {
            BlockState block = this.getBlockState(pos);
            if (!block.canOcclude()) {
                return null;
            }
            VoxelShape voxelshape = c.getBlockShape(block, this, pos);
            return this.clipWithInteractionOverride(c.getFrom(), c.getTo(), pos, voxelshape, block);
        }, (c) -> {
            Vec3 vec3 = c.getFrom().subtract(c.getTo());
            return BlockHitResult.miss(c.getTo(), Direction.getNearest(vec3.x, vec3.y, vec3.z),
                    new BlockPos(c.getTo()));
        });
    }

    @Override
    public int getHeight() {
        return 0;
    }

    @Override
    public int getMinBuildHeight() {
        return 0;
    }
}

 

Link to comment
Share on other sites

38 minutes ago, andreybadrey said:

import java.util.function.Predicate;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.VoxelShape;

public class RayTrace implements BlockGetter {
    private static Predicate<Entity> isVisible =
            entity -> !entity.isSpectator() && entity.isPickable();
    private static Minecraft minecraft = Minecraft.getInstance();

    @Override
    public BlockEntity getBlockEntity(BlockPos pos) {
        return minecraft.level.getBlockEntity(pos);
    }

    @Override
    public BlockState getBlockState(BlockPos pos) {
        return minecraft.level.getBlockState(pos);
    }

    @Override
    public FluidState getFluidState(BlockPos pos) {
        return minecraft.level.getFluidState(pos);
    }

    public LivingEntity getEntityInCrosshair(float partialTicks, double reachDistance) {
        Minecraft client = Minecraft.getInstance();
        Entity viewer = client.getCameraEntity();

        if (viewer == null) {
            return null;
        }

        Vec3 position = viewer.getEyePosition(partialTicks);
        Vec3 look = viewer.getViewVector(1.0F);
        Vec3 max = position.add(look.x * reachDistance, look.y * reachDistance, look.z * reachDistance);
        AABB searchBox =
                viewer.getBoundingBox().expandTowards(look.scale(reachDistance)).inflate(1.0D, 1.0D, 1.0D);

        EntityHitResult result = ProjectileUtil.getEntityHitResult(viewer, position, max, searchBox,
                isVisible, reachDistance * reachDistance);

        if (result == null || result.getEntity() == null) {
            return null;
        }

        if (result.getEntity() instanceof LivingEntity) {
            LivingEntity target = (LivingEntity) result.getEntity();

            HitResult blockHit =
                    clip(setupRayTraceContext(client.player, reachDistance, ClipContext.Fluid.NONE));

            if (!blockHit.getType().equals(BlockHitResult.Type.MISS)) {
                double blockDistance = blockHit.getLocation().distanceTo(position);
                if (blockDistance > target.distanceTo(client.player)) {
                    return target;
                }
            } else {
                return target;
            }
        }

        return null;
    }

    private ClipContext setupRayTraceContext(Player player, double distance, ClipContext.Fluid fluidHandling) {
        float pitch = player.getXRot();
        float yaw = player.getYRot();
        Vec3 fromPos = player.getEyePosition(1.0F);
        float float_3 = Mth.cos(-yaw * 0.017453292F - 3.1415927F);
        float float_4 = Mth.sin(-yaw * 0.017453292F - 3.1415927F);
        float float_5 = -Mth.cos(-pitch * 0.017453292F);
        float xComponent = float_4 * float_5;
        float yComponent = Mth.sin(-pitch * 0.017453292F);
        float zComponent = float_3 * float_5;
        Vec3 toPos = fromPos.add((double) xComponent * distance, (double) yComponent * distance,
                (double) zComponent * distance);
        return new ClipContext(fromPos, toPos, ClipContext.Block.OUTLINE, fluidHandling, player);
    }

    @Override
    public BlockHitResult clip(ClipContext context) {
        return BlockGetter.traverseBlocks(context.getFrom(), context.getTo(), context, (c, pos) -> {
            BlockState block = this.getBlockState(pos);
            if (!block.canOcclude()) {
                return null;
            }
            VoxelShape voxelshape = c.getBlockShape(block, this, pos);
            return this.clipWithInteractionOverride(c.getFrom(), c.getTo(), pos, voxelshape, block);
        }, (c) -> {
            Vec3 vec3 = c.getFrom().subtract(c.getTo());
            return BlockHitResult.miss(c.getTo(), Direction.getNearest(vec3.x, vec3.y, vec3.z),
                    new BlockPos(c.getTo()));
        });
    }

    @Override
    public int getHeight() {
        return 0;
    }

    @Override
    public int getMinBuildHeight() {
        return 0;
    }
}

 

Even better

Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • https://pastebin.com/FaQ43RnJ  Este es un error que me lanza al momento de querer iniciar forge Intente de todo pero no sirve nada. This is an error that I get when I want to start forge. I tried everything but nothing works.
    • It was a stupid Eclipse problem ,the debugger was set to a lower version of java.  In what world would i want my development version different from the debugger version.   ty for looking
    • Caused by: java.lang.NullPointerException: Cannot read field "level" because "this.minecraft" is null This is my first big error when coding. I looked it up, but there are a bunch of references to Dawncraft and not enough to figure out what was going wrong. I found this, but it involves a command and my GUI only opens when you shift + right-click while holding an item. They fixed it by not calling it with a command, but I am not using a command. Here's the render of my menu, which is the only part that changed between it working and not:   @Override public void render(@Nonnull PoseStack mstack, int mouseX, int mouseY, float partialTicks) { int midx = this.width / 2; int midy = this.height / 2; this.renderBackground(mstack); drawCenteredString(mstack, font, I18n.get("config.shape_tool"), midx, 4, 0xC3D1D8); Utils.renderImage(midx - 12, midy, 20, 20, "textures/gui/plus.png", mstack); addRenderableWidget(new Button(midx - 12, midy, 10, 10, Component.translatable(""), this::increaseax)); Utils.renderImage(midx + 12, midy, 20, 20, "textures/gui/minus.png", mstack); addRenderableWidget(new Button(midx + 12, midy, 10, 10, Component.translatable(""), this::decreaseax)); drawCenteredString(mstack, font, String.valueOf(shapetoolax), midx, midy + 10, 0xC3D1D8); super.render(mstack, mouseX, mouseY, partialTicks); } Utils.renderImage is this:   public static void renderImage(int x, int y, int width, int height, String img, PoseStack mstack) { RenderSystem.setShaderColor(1, 1, 1, 1); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.setShaderTexture(0, new ResourceLocation(PNegative.MODID, img)); blit(mstack, x, y, 0, 0, width, height, width, height); RenderSystem.disableBlend(); } I have used it before and it has worked, so it can't be a problem. 
    • I found a topic  with the very simmilar problems. I run modpack Direwolf20 1.19.2 version from FTB with dedicated server with my friends and i am the only who have this type of crashes. It has been through login process and after 5-6 crashes i can connect. And randombly it could crash me in game but mostly when i am tp'ing using Nether portals etc. I already setted up all privileges for javaw in firewall, flushed dns, reset network settings and etc. Changed java version to from FAQ too. Here's some logs from client side https://gnomebot.dev/paste/1158502890168664194 https://gnomebot.dev/paste/1158187264657063946    
    • Don't know why game keeps crashing after a few seconds or walking towards something, tried removing larger mods and someaddon performance mods but it's not working. Minecraft launchers telling me "Exit Code 1"
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.