Calculating distance between cords

Discussion in 'Plugin Development' started by blackvoid, Mar 29, 2011.

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

    blackvoid

    Hi i have a small problem.
    I made a equation to calculate the distance between 2 cordinates but it doesnt seem to work that good.
    I dont have much experience with Minecraft cordinates so i dont know how many units each block is and thats what i want the output to be.
    Code:
    static int CalculateDistance(Location L1, Location L2){
        if (L1.getWorld().equals(L2.getWorld())){
            int X;
            int Y;
            int Z;
            if(L1.getX() > L2.getX()){
                X = (int)(L1.getX()-L2.getX())^2;
            }else{
                X = (int)(L2.getX()-L1.getX())^2;
            }
            if(L1.getY() > L2.getY()){
                Y = (int)(L1.getY()-L2.getY())^2;
            }else{
                Y = (int)(L2.getY()-L1.getY())^2;
            }
            if(L1.getZ() > L2.getZ()){
                Z = (int)(L1.getZ()-L2.getZ())^2;
            }else{
                Z = (int)(L2.getZ()-L1.getZ())^2;
            }
            return (int) Math.sqrt(X+Y+Z);
        }
        return -1;
    }
     
  2. Offline

    Edward Hand

    First you should know that squaring a number gives the same result as squaring its negative (X^2 = (-X)^2). As such, those if/else blocks are not needed.
    Second, since we are not using Microsoft Excel or something, the symbol '^' does not represent 'to the power'. In java it is the bitwise XOR operator (which is entirely unrelated). To square use:
    Code:
    Math.pow(theNumber,2)
    You will also get higher accuracy if you don't round everything to integers every step of the way.

    However, bukkit has a built-in vector class capable of doing calculations like this for you.
     
  3. Offline

    blackvoid

    Im used to code in lua and php and then you use ^. Thanks for the help
     
  4. Offline

    Edward Hand

    Yeah. Everyone falls into that trap at first. ;)
     
Thread Status:
Not open for further replies.

Share This Page