How to check if player is close from a location

Discussion in 'Spigot Plugin Development' started by HotDoctor, May 25, 2019.

  1. What I'm trying to do is that every time a player moves, he checks that if the player is near an area (in this case, what I did was select a block as the center, and save the location of this block to a config.yml) but what I do not know how to do is that when a player enters an area (for example, 4 blocks) that is close to the center, take an action.

    Any help? please, thanks.
  2. Code (Java):

        public void movement(PlayerMoveEvent e) {
            Player player = e.getPlayer();
            if(main.getConfig().getString("boosters.enable").equalsIgnoreCase("true")) {
                for(String result : main.getConfig().getConfigurationSection("boosters.ids").getKeys(false)) {
                    if(main.getConfig().contains("boosters.ids."+result+".location")) {
                        int radius = main.getConfig().getInt("boosters.ids."+result+".booster-options.radius");
                        Location BoostLoc = locFromString(main.getConfig().getString("boosters.ids."+result+"location"));
                        if(BoostLoc.distanceSquared(player.getLocation()) == (radius^2) || BoostLoc.distanceSquared(player.getLocation()) > (radius^2)) {
                           //my stuff, for example, apply plotion to a player.
    Im not sure, but this should work, right?
  3. Test it ;)

    Instead of using getString("boosters.enable").equalsIgnoreCase("true"), use getBoolean("boosters.enable")
  4. Hello,

    ^ is a binary operator, not the "power" function. The correct way is by using Math#pow.
    Note that Location#distanceSquared throw IllegalArgumentException if the worlds aren't the same.
    Also note that you forgot a dot in your YAML node, before the location:
    #5 Andross, May 25, 2019
    Last edited: May 25, 2019
    • Friendly Friendly x 1
  5. it's power 2 so we can use Math#square
    #6 Il_totore, May 26, 2019
    Last edited: May 26, 2019
  6. Math#square doesn't exists :LOL:
    T'es mignon, mais quand même.. :giggle:
  7. Whoops. Square root exists but not square o_O
    Je sais je suis trop mignon :p