我如何找到这三点之间的距离java

时间:2015-11-05 15:48:51

标签: java distance

我需要弄清楚每个士兵之间的距离,但我无法弄清楚如何,因为他们都来自相同的xPos和yPos,我在网上找到的一切都是针对x1,y1,x2,y2的情况。

这个想法是他们随机产生然后可以移动攻击彼此,但我需要知道他们之间的距离才能继续

public class Soldier {

    double xPos;
    double yPos;

    public Soldier(/*double distance, double speed*/) {
        double lower = 0;
        double upper = 100; //setting the upper and lower limits for the soldiers
        xPos = Math.random() * (upper - lower) + lower;
        yPos = Math.random() * (upper - lower) + lower; //creating x and y values
        xPos = Math.round(xPos * 10) / 10.0d;
        yPos = Math.round(yPos * 10) / 10.0d; //making sure the x and y value is to 1dp
        System.out.println("(" + xPos + ", " + yPos + ")"); //printing the location
    }
}

我的主要课程是,

public class Main {                                   
   public static void main(String[] args) {           
       Soldier Cavalier = new Soldier(/*5.9, 1*/);    
       Soldier Pikeman = new Soldier(/*10.3, 12.6*/); 
       Soldier Crossbowman = new Soldier(/*4.9, 3*/); 
       System.out.println();                          
   }         
}     

1 个答案:

答案 0 :(得分:3)

在士兵类上添加distanceTo方法:

public class Soldier {
    ....

    public double distanceTo(Soldier other) {
        return Math.sqrt(Math.pow(other.xPos-this.xPos,2) + Math.pow(other.yPos-this.yPos,2));
    }
}

然后使用它:

   Soldier Cavalier = new Soldier();    
   Soldier Pikeman = new Soldier(); 
   System.out.println(Cavalier.distanceTo(Pikeman)); 

由于评论员和#39;而添加建议:

只是提一下,Math.pow是幂函数的一般实现,能够计算任何类型参数的功效。因此,它比简单的x * x类型乘法慢很多。此代码的优化版本如下所示:

    public double distanceTo(Soldier other) {
        double dx = other.xPos-this.xPos;
        double dy = other.yPos-this.yPos;
        return Math.sqrt(dx*dx + dy*dy);
    }

如果您不需要性能优化,可以使用任何更易读的版本。