Finding nearest player with a compass?

Discussion in 'Plugin Development' started by 1928i, Feb 11, 2015.

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

    1928i

    I've seen many people use tracking compasses that say the nearest non-spectator and have the needle point towards them. I have absolutely no idea how to do this and searching it hasn't helped me at all. Does anyone know how to do this?
     
  2. Offline

    Gater12

    @1928i
    Loop through the players and see which one is closest. Then set the player's compass location to the nearest player's location.
     
  3. Offline

    1928i

    @Gater12
    How do I see which one is closer and how do you set a compass's location?

    Does anyone know how?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2016
  4. Offline

    Skionz

  5. Offline

    1Rogue

    https://github.com/CodeLanx/Codelan...om/codelanx/codelanxlib/util/Players.java#L89

    Code:java
    1. /**
    2.   * Returns the closest {@link Player} adjacent to another {@link Player}
    3.   *
    4.   * @since 0.1.0
    5.   * @version 0.1.0
    6.   *
    7.   * @param p The {@link Player} at the origin to search around
    8.   * @return The closest {@link Player}, or {@code null} if no one else is in
    9.   * the world
    10.   */
    11. public static Player getClosestPlayer(Player p) {
    12. Location loc = p.getLocation();
    13. return p.getWorld().getPlayers().stream()
    14. .filter((o) -> !p.equals(o))
    15. .min((p1, p2) -> {
    16. return Double.compare(p1.getLocation().distanceSquared(loc), p2.getLocation().distanceSquared(loc));
    17. })
    18. .orElse(null);
    19. }


    Which in Java 7 or less would look like:

    Code:java
    1. public static Player getClosestPlayer(Player origin) {
    2. Validate.notNull(origin, "Player cannot be null!");
    3. double min = Double.MAX_VALUE;
    4. Player closest = null;
    5. for (Player p : p.getWorld().getPlayers()) {
    6. if (p == origin) {
    7. continue;
    8. }
    9. double d = origin.getLocation().distanceSquared(p.getLocation());
    10. if (d < min) {
    11. min = d;
    12. closest = p;
    13. }
    14. }
    15. return closest;
    16. }
     
  6. Offline

    1928i

    @1Rogue
    Two things:
    One, how would I make it so that it would be the closest player in survival mode.
    Two, could you explain the code a little better? I am trying to understand it but I get lost.
     
  7. Offline

    WesJD

  8. Offline

    1Rogue

    Check their gamemode when you iterate through the players.

    What this does is merely take all the players in the same world as the original player, goes through each one, and compares the distance they are from the player each time until it finds the smallest value.
     
Thread Status:
Not open for further replies.

Share This Page