Basti
Basti

Reputation: 1186

Check precisely if two rectangles with double coordinates intersect

I was playing arround with hitboxes and ended up with following data:

final double targetSmallestX = targetCenter.getX() - targetHalfWidth;
final double targetSmallestY = targetCenter.getY() - targetHalfHeight;
final double targetHighestX = targetCenter.getX() + targetHalfWidth;
final double targetHighestY = targetCenter.getY() + targetHalfHeight;
final double sourceSmallestX = sourceCenter.getX() - sourceHalfWidth;
final double sourceSmallestY = sourceCenter.getY() - sourceHalfHeight;
final double sourceHighestX = sourceCenter.getX() + sourceHalfWidth;
final double sourceHighestY = sourceCenter.getY() + sourceHalfHeight;

What i want to do is to check, if the two given rectangles target and source are intersecting with each other. Could have done it like this

Rectangle target = new Rectangle(targetSmallestX, target.width, targetSmallestY, target.height);
Rectangle source = new Rectangle(sourceSmallestX, source.width, sourceSmallestY, source.height);
target.intersect(source);

But this would require me to work with integers.
All the algorithms I came up with seemed too long and complicated for such a seemingly simple task. Does anyone have an idea for a smart approach for this?

EDIT:
Current approach

(targetSmallestX < sourceSmallestX + this.width)
&& (sourceSmallestX < (targetSmallestX + target.width))
&& (targetSmallestY < sourceSmallestY + this.height)
&& (sourceSmallestY < targetSmallestY + target.height);

Does this check leave any possible constellations in which it wouldn't work correctly?

Upvotes: 0

Views: 71

Answers (1)

k_ssb
k_ssb

Reputation: 6282

In Java, you can use java.awt.geom.Rectangle2D which represents coordinates with floating-point precision. Precisely, its inner class java.awt.geom.Rectangle2D.Double uses double to represent the coordinates.

Rectangle2D target = new Rectangle2D.Double(targetSmallestX, targetSmallestY, target.width, target.height);
Rectangle2D source = new Rectangle2D.Double(sourceSmallestX, sourceSmallestY, source.width, source.height);
target.intersect(source);

Upvotes: 1

Related Questions