2

I use Java Swing to create simple games such as Pong and Air Hockey, and I often find myself using Pythagoras Theorem to calculate the distance between two points.

Although it's not a pain to write (it can be reduced to a single line), I was wondering if Java had already included it somewhere.

I looked through the Math class, and I didn't see anything there. I didn't know where else to look, so if it does exist, does anyone know where?

Thanks!

John S.
  • 626
  • 1
  • 4
  • 16

3 Answers3

6

Yes, Java has such a function in the standard library. It is called Math.hypot. So you can write:

Math.hypot(x2 - x1, y2 - y1)

This method is part of Java since Java 1.5.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Hoopje
  • 12,677
  • 8
  • 34
  • 50
1

You can use the java awt.geom classes for that. Particularly, look at Point2D here

Note, that these classes are designed for graphical interfaces, and use plot points starting from the top left at 0,0, increasing as the go further right and down. So for x=2, y=3, this point is three points down, and two points right of the top-left of the plot.

You can both use the class in a static way:

Point2D.distance(x1, y1, x2, y2);

But also in an oo way:

Point2D point1 = new Point2D.Double(x1, y1);
point1.distance(x2, y2);
point1.distance(new Point2D.Double(x2, y2));

I mention these libraries not because they're the easiest to use (Math library is the most straight forward to find the distance between two points), but you're talking about 2D graphical programs. And there's a lot of good stuff in the java geom libraries aimed at this sort of thing. So if you want to work out whether your point is inside a square (or any other shape for instance), you can do that. Or if you want to work out if one shape intersects with another, or if two lines cross, you can do that as well.

AndyN
  • 2,075
  • 16
  • 25
1

If you are using Swing/AWT you can represent your coordinates as java.awt.geom.Point2D or java.awt.Point which is a subclass of the first. On that class you have the method distance(Point2D), which gives you the desired result.

If you decide to switch from Swing to JavaFX you can use javafx.geometry.Point2D which provides the same functionality.

hotzst
  • 7,238
  • 9
  • 41
  • 64