Solved Find Closest Location to Player from Existing List of Locations?

Discussion in 'Plugin Development' started by CreativeUsername, Apr 11, 2018.

Thread Status:
Not open for further replies.
  1. Let's pretend we have two locations defined. They are color coded in the image (as blue and green.)

    [​IMG]

    This map is part of an RPG server, and I'm working on an after-death system. Essentially, after you die, you are teleported to the nearest village (a defined location.) So in this image, I would be teleported to the green dot instead of the blue dot, due to the fact that I am closer to the green dot.

    Is this possible? Perhaps I have an ArrayList<Location> or some other, can loop through it and compare the distances?

    No need to spoonfeed me code, I'm sure I can figure this out myself, but I'm not sure how to compare the distance between the player and each location, then use the lowest one.

    Thanks :)
     
  2. Offline

    Zombie_Striker

    @CreativeUsername

    Location#distance( Location ) returns the distance between two locations.

    [Edit] To find the closest one, create an double variable and a Location variable. the double will be the closest distance and the Location will be the closest location. Set the double equal to the max value. Then, loop through all of the possible locations and check if each location is less than that double, and if so, set the double equal to the distance and the location equal to that location.
     
    CreativeUsername likes this.
  3. List of locations (serializable) in config.
    On enable or on reload or whatever, load in all locations to a List or Set
    When player dies, make a new Map ( Distance to Player, Location) of Location#distanceSquared (quicker than #distance and will still produce the same results). Perform some sort of Collection.sort on Map#keySet to get the lowest distance. Finally, just use Map#get with the distance and teleport them there

    Hope this helps.


    Edit: not sure if @Zombie_Striker's method is faster, but in my experience Location#distanceSquared is definitely faster and will still work fine (as long as you're squaring all distances, it won't change)
    Sent from my SM-G903F using Tapatalk
     
    CreativeUsername likes this.
  4. Offline

    Zombie_Striker

    @TheMinecraftKnight
    .distance() and distanceSquared() could be used, it just depends on what you need it for, since distnaceSquared does not find the squar root for the distance.

    Basically, if you need to know the exact distance, use distance(). If you only care about finding which one is closest without actually knowing the exact distance, then use distanceSquared().
     
    Googlelover1234 likes this.
Thread Status:
Not open for further replies.

Share This Page