0

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
bsharp313
  • 11
  • 1
  • 2
    Possible duplicate of [How to make the division of 2 ints produce a float instead of another int?](http://stackoverflow.com/questions/787700/how-to-make-the-division-of-2-ints-produce-a-float-instead-of-another-int) – resueman Mar 29 '16 at 01:06

2 Answers2

4

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Or better yet, use [`Math.sqrt(double a)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#sqrt%28double%29). – Andreas Mar 29 '16 at 01:12
1

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
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51