Here is a method to get the entity that a player is looking at, if any at all:
public Entity getTargetEntity(Player player) {
int r = 100;
for (Entity entity : player.getNearbyEntities(r, r, r)) {
if (entity instanceof LivingEntity) {
LivingEntity livingEntity = (LivingEntity) entity;
Location eye = player.getEyeLocation();
Vector toEntity = livingEntity.getEyeLocation().toVector().subtract(eye.toVector());
double dot = toEntity.normalize().dot(eye.getDirection());
if (dot > 0.99D) {
return entity;
}
}
}
return null;
}
Calling the method getTargetEntity(player)
will return an Entity
object if any is detected in the line-of-sight of the Player
input parameter, or returns null
if no Entity
is detected.
The value of the int
r
near the start of the method determines how far (in blocks) to search for mobs from the player, in all directions (the x-, y-, and z-coordinates).
In this example, it is set to 100
, however the method will be more accurate with higher numbers. Just remember that means more entities will be checked every time the method is run, which may eat up significant server resources.
To use in the code above, for instance, to detect if it is a Player
that is being looked at, or "targeted":
public void entityLookingAt(Player p){
if(getTargetEntity(p) instanceof Player){
p.sendMessage("You're looking at a player!");
}
}
This should work up to at least v1.21.1
. Hopefully, this will help anyone who may have a similar question in the future.