2016-03-29 16 views
0

Fareyle hareket eden bir nesne arasındaki mesafeyi kontrol etmek için mesafe formülünü kullanmam gerekir. Ancak, totalDistance yalnızca 1'e geri dönmeye devam ediyor ve neden emin değilim.Java'da mesafe formülünü kullanma

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

Tekrarlama olabilir [2 ints bölünme yerine başka bir int bir float üretmek nasıl yapılır?] (Http://stackoverflow.com/questions/787700/how-to-make-the-division- of-2-ints-üretmek-a-float yerine-başka-int) – resueman

cevap

4

Sen tüm üs hesaplamalar için double hassasiyet belirterek edilmelidir:

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

Aslında toplam mesafe için hesaplama Ben büyük bir potansiyel problem gördüğümüz tek yerdi. Bunu vardı:

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

Buradaki sorun sadece arasındaki mesafeyi hesaplamak için Point2D::distance kullanabilirsiniz (1/2) tamsayı bölme olarak kabul edilecektir ve sonuç 0. Java'da

+1

Veya daha iyisi, ['Math.sqrt (double a)'] kullanın (https://docs.oracle.com/javase/ 7/docs/aPI/java/lang/Math.html # sqrt% 28double% 29). – Andreas

1

göre kesilecek olmasıdır iki puan.

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