[solved] Finding the distance between 2 rectangles

Hey JGO, I’m having difficulty’s calculating the distance between 2 tiles in my game.
(Attempting to implement a A* Pathfinding system)

Rather noob question but I’m stumped.

Is there a method for java.awt.Rectangle that would allow me to calculate the distance beetween the 2 rectangles or any other util method like it?

Thanks for any help/feedback :slight_smile:

Distance between their centers? Between closest edges? What?

Sorry, I added a picture to better explain.
(from the tile.x, which will be the tiles top left, correct?)

I wouldn’t like to obtain the center points as this is for A* Pathfinding and i’d have to do extra math to correct them.

Thanks for replying. :slight_smile:

http://static.prometheanplanet.com/images/resources/resource-thumbnails/thumb-nalg1-13-03-0001-diagram-thumb-lg-png.png


double distance(int x1, int y1, int x2, int y2) {
    int dx = x2 - x1;
    int dy = y2 - y1;
    return Math.sqrt(dx * dx + dy * dy);
}

Distance between centers of uniform rectangles is actually equivalent to distance between like corners anyway.

I’m a derp, thanks.

I had a formula that came up with the distance correctly like yours does (rather long lol) @ first but I misunderstood it visually and came here posting for help lol. (Distance was 45, i was expecting 32 XD)

There’s also different kinds of distance, that may or may not be useful depending on how you want your A* etc to act.

Notably the difference between euclidean (what I posted) and manhattan (or taxicab) distance.

Thanks I was actually using your euclidean and wondering why results were funny, switched it to manhattan and now it’s fine :slight_smile:

Im guessing this was calculating the heuristic. Good to see you sorted it out.

I like the Euclidean method better because it looks really tidy. Not much going on, and it’s easily expandable to different dimensions. But whatever works :slight_smile:

Eh:
(for n-dimensional vectors p and q)
Euclidean: d(p, q) = √(Σ(qi - pi)2)
Manhattan: d1(p, q) = Σ|pi - qi|

You have a point, but in code euclidean looks better, no? In the end it doesn’t really matter anyways :stuck_out_tongue:

If you only want to COMPARE distances (like a heuristic in A*) you can also
leave out the square root, and just calculate c1 = aa + bb

then see wich distance is closer, eg. c1 > c2 etc,

This gives you a big performance boost skipping the expensive Math.sqrt()


double distanceRaw(int x1, int y1, int x2, int y2) {
    int dx = x2 - x1;
    int dy = y2 - y1;
    return (dx * dx + dy * dy);
}