Skip to content

Commit 5ff6ea8

Browse files
committed
Add method to get the nearest player to a specified location
1 parent bbb90a3 commit 5ff6ea8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

SimpleAPI/src/main/java/com/bencodez/simpleapi/player/PlayerUtils.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import java.net.URL;
1010

1111
import org.bukkit.Bukkit;
12+
import org.bukkit.Location;
1213
import org.bukkit.block.Block;
1314
import org.bukkit.block.BlockFace;
1415
import org.bukkit.command.CommandSender;
@@ -184,6 +185,37 @@ public static IServerHandle loadHandle() {
184185
return serverHandle = new CraftBukkitHandle();
185186
}
186187
}
188+
189+
/**
190+
* Gets the nearest player to the given location within the specified max distance.
191+
*
192+
* @param location The center location to search from.
193+
* @param maxDistance The maximum distance (in blocks).
194+
* @return The nearest Player, or null if none are within range.
195+
*/
196+
public static Player getNearestPlayer(Location location, double maxDistance) {
197+
if (location == null || location.getWorld() == null) {
198+
return null;
199+
}
200+
201+
Player nearest = null;
202+
double maxDistanceSquared = maxDistance * maxDistance;
203+
double closestSoFar = maxDistanceSquared;
204+
205+
for (Player player : Bukkit.getOnlinePlayers()) {
206+
if (player.getWorld() != location.getWorld()) {
207+
continue;
208+
}
209+
210+
double distanceSquared = player.getLocation().distanceSquared(location);
211+
if (distanceSquared <= closestSoFar) {
212+
closestSoFar = distanceSquared;
213+
nearest = player;
214+
}
215+
}
216+
217+
return nearest;
218+
}
187219

188220
private static java.util.UUID parseUUIDFromString(String uuidAsString) {
189221
String[] parts = { "0x" + uuidAsString.substring(0, 8), "0x" + uuidAsString.substring(8, 12),

0 commit comments

Comments
 (0)