Or, to get the single-most closest entity:
public Entity getClosestEntity(final Player player) {
Entity closest = null;
double closestDistance = 0;
for (Entity entity : player.getLocation().getExtent().getEntities()) {
if (entity == player) {
continue;
}
double distance = entity.getLocation().getPosition().distance(player.getLocation().getPosition());
if (closest == null || distance < closestDistance) {
closest = entity;
closestDistance = distance;
}
}
return closest;
}
A marked downfall, if you can call it that, is that in the off-chance that there are two entities which are exactly the same distance away (which, to be fair, is unlikely when you’re comparing doubles), it’ll only give you the first one to be looped over.