#How to get the entity the player is looking at?
12 messages · Page 1 of 1 (latest)
I'm with him. We're in 1.20.2, fabric loader version 0.15.11
Here's a method we're testing with, it NEVER returns "Entity" it's always "Block" or null. Any ideas why it's just skipping past any entities? What are we doing wrong? This code is running on main on the server not the client
private String getTargetType(PlayerEntity player, double range, boolean includeFluids) {
HitResult hitResult = player.raycast(range, 1.0F, includeFluids);
if (hitResult.getType() == HitResult.Type.ENTITY) {
return "Entity";
} else if (hitResult.getType() == HitResult.Type.BLOCK) {
return "Block";
} else {
return null;
}
}```
A quick look in the source reveals it only tests against blocks (and fluids if includeFluids is true)
How do I get a player's target entity then?? Surely you can do that somehow
Also I find it dumb that there's even an entity HitResult type if it can't hit entities -_-
Unless someone else has a better way, this is what we're doing.
Just looking every 0.1 blocks and seeing if there's an entity
public static Entity getTargetEntity(PlayerEntity player, double range) {
// Look, I'm aware that this is possibly the stupidest way to do this. However. It's the only way I knew how
// Hours were spent looking for a better way, we're flippin' using this.
ServerWorld world = ((ServerWorld) player.getWorld());
Vec3d playerPos = player.getCameraPosVec(1.0F);
Vec3d lookVec = player.getRotationVec(1.0F);
// Calculate step vector in the direction of the player's look vector
Vec3d stepVec = lookVec.multiply(0.1);
// Iterate through points along the line of sight up to MAX_DISTANCE
for (double distance = 0.0D; distance <= range; distance += 0.1) {
Vec3d point = playerPos.add(lookVec.multiply(distance));
double leeway = 0.05;
Box searchBox = new Box(point.getX() - leeway, point.getY() - leeway, point.getZ() - leeway,
point.getX() + leeway, point.getY() + leeway, point.getZ() + leeway);
// Check for entities within the search box
for (Entity entity : world.getOtherEntities(player, searchBox)) {
if (entity != player && entity.getBoundingBox().intersects(searchBox)) {
return entity;
}
}
}
return null; // No entity found within MAX_DISTANCE
}```
This probably works but I know of the variable MinecraftClient#lookingEntity (or something along those lines), I see you want this on the server but I would look at the code to where that entity get's written to, for reference on how to do it
but that's on the client which is what I said
