A good way to do this? (Grabbing entities near a location)

Discussion in 'Plugin Development' started by nossr50, Apr 22, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    nossr50

    Is there a good way to find out if an entitiy is near a location without looping through every entity in the world and comparing the distance between their locations?

    Like say I want to grab all Creepers near a block, is there a way to do this without checking every instance of a Creeper in the worlds entity list's distance from the block?

    I'm just worried looping through every entity and doing distance calculations would be a too much burden on servers.
     
  2. Offline

    matter123

    well you could just keep track of creepers and loop through that list
     
  3. Offline

    Carnes

    Yeah, i think matter123 has a good solution to start with. You can build two lists too. One is checked every few ticks and the other only every 10 secs or so. If a mob is close to one of your points, you promote it to the list that is checked more often.

    This wouldn't even be visible on a cpu graph, don't sweat it.
     
  4. Offline

    eisental

    You can use this to find if they're in range:
    Code:
        public static boolean isInRadius(Location origin, Location loc, double radius) {
            return Locations.distanceSquared(origin, loc) <= radius*radius;
        }
    
        public static double distanceSquared(Location loc1, Location loc2) {
            double dx = loc1.getX() - loc2.getX();
            double dy = loc1.getY() - loc2.getY();
            double dz = loc1.getZ() - loc2.getZ();
    
            return dx*dx + dy*dy + dz*dz;
        }
    
    
    Should be faster without making any new Vecotr objects (in case you were using the bukkit Vector class) and doesn't use Math.pow() or Math.sqrt(). You could also calculate which chunks you're tracking and only check entities in those chunks with Chunk.getEntities().
     
Thread Status:
Not open for further replies.

Share This Page