Distance formula in Java?

I don’t know if it has something to do with OpenGL or it’s just Java in general but…

distance = (int) Math.sqrt(((ent.getX() - x) ^ 2) + ((ent.getY() - y) ^ 2));

I sometimes get NaN from that.

Although, if I move it around like this…

distance = (int) Math.sqrt(((x - ent.getX()) ^ 2) + ((y - ent.getY()) ^ 2));

Instances where it would NaN would return normal numbers, but on the otherhand the instances where it returns a normal number is now NaN.

What did I do wrong? Both X/Y’s are on concurrent matrices, so what is it?

value ^ 2

means XOR

you either need:

return (int) Math.sqrt(Math.pow(x - ent.getX()), 2.0) + Math.pow(y - ent.getY(), 2.0));

or more readable and much faster:


dx = x - ent.getX();
dy = y - ent.getY();
return (int)Math.sqrt(dx*dx + dy*dy);

Thanks!!

Also there’s distance method on… Point/Point2D.