I've pondered over this problem for a long time, and was just wondering if there really was a better way to get nearby entities instead of looping through every entity in the world and testing their location?
For the plugin I'm developing, I'm using this every tick and in no way at all is it efficient.
public static List<Entity> getEntitiesAroundPoint(Location location, double radius) {
List<Entity> entities = new ArrayList<Entity>();
for (Entity entity : location.getWorld().getEntities()) {
if (entity.getWorld() != location.getWorld()) {
continue;
} else if (entity instanceof Player && ((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) {
continue; //Don't want spectators
} else if (entity.getLocation().distanceSquared(location) <= radius * radius) {
entities.add(entity);
}
}
return entity;
}
I don't have access to a player object so player.getNearbyEntities()
isn't really an option (and I don't know if that is any better, either). I did wonder if location.getChunk().getEntities()
would be any better to loop but again, I have no idea of the process behind that. Could anyone share some insight with me as to what might be a better way to go about this effeciently?
Thanks in advance.