Solved Check if player enters or exits the location?

Discussion in 'Spigot Plugin Development' started by kinukin, Feb 4, 2020.

  1. How can I check if a player enters or exits the location?

    I've tried this but it says you have exited when you enter.

    Code (Text):
    if(p.getLocation().distance(location) <= 10) {
    System.out.println("you have entered");
    } else {
    System.out.println("you have exited");
    }
     
    #1 kinukin, Feb 4, 2020
    Last edited: Feb 4, 2020
  2. You'd want to either schedule a task or listen to PlyerMoveEvent and then compare the player's positions to see if the player moved from outside to inside the location or vice versa.
     
  3. I've tried this but it says you have exited when you enter.

    Code (Text):
    if(p.getLocation().distance(location) <= 10) {
    System.out.println("you have entered");
    } else {
    System.out.println("you have exited");
    }
     
  4. Obviously if you’re running that statement unconditionally...
     
  5. How do I fix that?
     
  6. It means that something isn’t right in your statement. Can I see what location is?
     
  7. Code (Text):
    Location location = new Location(Bukkit.getWorld("world"), -65.217, 85, -49.124);
     
  8. Try getting the distance using getX(), getY(), getZ() on a PlayerMoveEvent.
     
  9. Isn't that the same?
     
  10. Try to do a little debug.
    Code (Java):
    double distance = p.getLocation().distance(location);
    if(distance <= 10) {
        System.out.println("you have entered " + distance);
    } else {
        System.out.println("you have exited " + distance);
    }
    Also, if you don't need a real distance there, for optimization purposes it is better to use Location#distanceSquared instead of Location#distance. It will return you squared distance (distance^2), and just compare it with the distance that you need but squared too.
    Code (Java):
    double distance = p.getLocation().distanceSquared(location);
    if(distance <= 100) { // 10^2 = 100
        System.out.println("you have entered " + distance);
    } else {
        System.out.println("you have exited " + distance);
    }
     
  11. Strahan

    Benefactor

    Works fine for me. Just bear in mind it will spam "you have exited" constantly unless you apply a filter. Like a map that records when someone enters, so when dist > 10 it will only say "you've exited" if they are in the map, then it removes them from the map to prevent further messages.

    Also don't use system println, use the logger, that's why it is there. getLogger().info("I'm a console message!");.
     
  12. It says you have exited even if you are outside the bounds of the distance. I only want it to say you have exited when you leave the area.

    Note: This happens when you reload the server and is outside the distance area.
     
  13. Strahan

    Benefactor

    Right, because as I said you need to filter it.