bsharp313
bsharp313

Reputation: 11

Using distance formula in Java

I need to use the distance formula to check the distance between my mouse and a moving object. However, my totalDistance continues to return only 1 and I am not sure why.

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

Upvotes: 0

Views: 530

Answers (2)

Stefan Dollase
Stefan Dollase

Reputation: 4620

In Java, you can simply use Point2D::distance to calculate the distance between two points.

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

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

You should be specifying double precision for all your exponent calculations:

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

Actually, the calculation for total distance was the only place where I saw a big potential problem. You had this:

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

The problem here is that (1/2) will be treated as integer division, and the result will be truncated to 0.

Upvotes: 3

Related Questions