2016-03-29 5 views
0

私のマウスと動くオブジェクトとの距離を調べるには距離式を使用する必要があります。しかし、私のtotalDistanceは1に戻り続けています。理由はわかりません。あなたはすべてのあなたの指数の計算にdouble精度を指定する必要がありますJavaの距離式を使用する

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

の可能性のある重複した[2つのint型の除算を作成する方法ではなく、別のint型のフロートを作ります?](http://stackoverflow.com/questions/787700/how-to-make-the-division- of-2-ints-produce-a-float-another-int-int) – resueman

答えて

4

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))); 

ここでの問題は、あなたは単に間の距離を計算するためにPoint2D::distanceを使用することができ、(1/2)は整数の割り算として扱われ、その結果が0 Javaでは

+1

または、より良い方法では、['Math.sqrt(double a)'](https://docs.oracle.com/javase/) 7/docs/api/java/lang/Math.html#sqrt%28double%29)。 – Andreas

1

に切り捨てされるということです2点。

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