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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I downloaded forge for 1.21 because I wanted to play the new update with a few mods. When I load up the game on the forge installation, the game seems to launch fine, but then freezes and goes into that "not responding" state a few seconds after sitting on the menu. It stays on not responding forever, and I have to close the game myself. The normal vanilla game without forge loads and works perfectly fine, though. The exit code I receive is either 1 or -805306369, depending on how I close the game. When I force close with task manager, I get exit code 1. When I close using the not responding menu (close the program or wait for it to respond), I get exit code -805306369. I tried taking all of the mods out to see if they were the problem, but the same issue still persists even with 0 mods in the mods folder. The pastebin linked is the log from when I launched the game with forge after taking all of the mods out of the mods folder. (Nothing ever shows up in the crash-reports folder, but I do have this from the logs): https://pastebin.com/9bL8awvE I had to delete some of the bottom of the log to be able to upload it onto pastebin, but anything deleted was identical to the lines there at the bottom. Some things I have tried include: Allocating more ram, updating display drivers, updating java version (currently have Java 21, tried switching to java 17 but that did not work either), removing or changing settings on programs that may conflict with minecraft (followed this list https://minecrafthopper.net/help/known-incompatible-software/). None have worked so far. I'm aware of course that this is a beta version of forge, but I just wanted to see if there was something I could do to fix this, or if I will just need to wait for a more stable, non beta version to be released.  
    • sorry if this is an incorrect log or wrong tag ive never used this before and im new to modding latest log: file:///C:/Users/jason/curseforge/minecraft/Instances/Cottage Witch/logs/latest.log
    • Hi its me from my first account. I added creative core but when i start minecraft he gives me an error. Now i can't send you the log but I will later 
    • I want my mod to add two new NBT values to Block Displays and Item Displays (Like left-rotation, scale, transformation, etc.), which I call texture_repetition and texture_shift (both Vector3f variables). Texture_repetition allows the Display to repeat its texture or only show part of it, and the texture_shift value allows you to shift to the part of the texture you want the display to show. I already tried Mixins, and I assume I need to use the renderstate() function and entityData variable, but entityData is protected, which means I can not edit it using Mixins. How would I add these NBT values to the Display class without using the entityData class? (These two data values, if coded correctly, could allow slabs/stairs/walls of any block to be represented using Displays without being limited by the vanilla inventory options)
  • Topics

×
×
  • Create New...

Important Information

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