在Java中使用距离公式

时间:2016-03-29 01:01:13

标签: java formula distance

我需要使用距离公式来检查鼠标和移动物体之间的距离。但是,我的totaldistance继续只返回1,我不知道为什么。

float mouseX = Engine.getMouseX(); //gets X coordinate of the mouse
float mouseY = Engine.getMouseY(); //gets Y coordinate of the mouse

graphic.setDirection(mouseX,mouseY); //object faces mouse
float currentX = graphic.getX();  //gets X coordinate of object
float currentY = graphic.getY();  ////gets Y coordinate of object
double distanceX = (Math.pow((currentX - mouseX), 2)); //calculate (x2-x1)^2
double distanceY= (Math.pow((currentY - mouseY), 2)); //calculate (y2-y1)^2
double totalDistance = (Math.pow((distanceX+distanceY), (1/2))); 
//calculate square root of distance 1 + distance 2
System.out.println("totalDistance = "+totalDistance); //prints distance

2 个答案:

答案 0 :(得分:4)

您应该为所有指数计算指定double精度:

double distanceX = (Math.pow((currentX - mouseX), 2.0d));
double distanceY= (Math.pow((currentY - mouseY), 2.0d));
double totalDistance = (Math.pow((distanceX+distanceY), 0.5d));

实际上,总距离的计算是我看到一个很大的潜在问题的唯一地方。你有这个:

double totalDistance = (Math.pow((distanceX+distanceY), (1/2)));

这里的问题是(1/2)将被视为整数除法,结果将被截断为0。

答案 1 :(得分:1)

在Java中,您只需使用Point2D::distance来计算两点之间的距离。

    System.out.println(Point2D.distance(0, 3, 4, 0));
    // prints 5.0