If I have a location within a world selected, and have a "safe zone" around that location that say extends 500 blocks (creating a circle) (this means a player can be within 500 blocks of that location and be "safe"). how can I find the distance from the players location to the nearest safe area? Or what in this case would be the nearest edge of that circle?
To find the distance of a player to a given safe zone you simply need to find their distance to the center of the safe zone and then subtract the radius. This is because the shortest vector to the edge of the circle will be normal to the boundary and therefore parallel to a radius passing through the center of the circle.
Given the (x,y)
coordinates of the center of a safe zone, (x1,y1)
and the coordinates of the player, (x2,y2)
, you can calculate the distance to the center of the safe zone like this:
double distance = Math.sqrt(Math.pow(x1-x2,2) + Math.pow(y1-y2,2));
To compare which safe zone you are closest to you could wait to subtract the radius length to prevent wasted calculations.
Sorting through a list of safe zones may look something like this:
public double distanceToNearestSafeZone(Player player, List<SafeZone> safeZones) {
double distance;
double minimumDistance = Double.POSITIVE_INFINITY;
for(SafeZone safeZone:safeZones) {
distance = Math.sqrt(Math.pow(player.x-safeZone.x,2) + Math.pow(player.y-safeZone.y,2));
if(minimumDistance > distance) {
minimumDistance = distance;
}
}
return minimumDistance - SafeZone.radius;
}
In this example the player object has a two public double
fields x
and y
holding the players position. The SafeZone
objects have similar fields. SafeZone
also has a public static double radius
field.
I hope this helps!