Closest player from clicker

Discussion in 'Plugin Development' started by Konkz, Mar 20, 2014.

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

    Konkz

    Hello,

    I am trying to get the nearest player from the position of the player that clicks the item in their inventory, I tried to use multiple codes I found on the internet before posting this but I could not achieve my result.

    I am trying to make it so when you click the item, it check if you're in the arraylist "cooldownsender", if you're not in it then it gets nearest player. If nearest player is in the array list "cooldowntarget". If they are not in it then it will execute rest of my code, but whenever I try to do it with different codes I keep failing.

    By any chance, does anyone have snippets of code that I would be able to review in order to improve my knowledge in this and continue my plugin?

    Thanks.
     
  2. Offline

    Noxyro

    Code:java
    1. Player player = clickingPlayer;
    2. double x, y, z; // Your bounding box for the selection
    3.  
    4. Player closest = null;
    5. double closestDistance = 0;
    6.  
    7. for (Entity entity : player.getNearbyEntities(x, y, z)) {
    8. if (entity instanceof Player) {
    9. double distance = player.getLocation().distance(entity.getLocation());
    10. if (distance < closestDistance || distance == 0) {
    11. closest = (Player) entity;
    12. closestDistance = distance;
    13. }
    14. }
    15. }
    16.  
    17. if (closest != null) {
    18. System.out.println(closest.getName() + " is the nearest player!");
    19. }
     
  3. Offline

    Konkz


    Thanks, I played with it for few hours and got it to work for my needs.
    Just a little question, how can I return a message saying "No players in your range" using that code?
     
  4. Offline

    Noxyro

    Add an else to if (closest != null) maybe? :p
    player.sendMessage("No playas in da range, yo!");
     
  5. Offline

    Konkz


    Tried it, it turns into dead code, that's my problem :p
     
  6. Offline

    Noxyro

    But it shouldn't :confused:

    Code:java
    1. if (closest != null) {
    2. player.sendMessage(closest.getName() + " is the nearest player!");
    3. } else {
    4. player.sendMessage("No players in your range!");
    5. }
     
  7. Offline

    Konkz

    [​IMG]

    Noxyro

    EDIT: Also returns a null exception error when I attempt to use the item and nobody is in the range.
     
Thread Status:
Not open for further replies.

Share This Page