I have this code:
public void paint(Graphics g) {
g.setColor(Color.black);
g.fill3DRect(myX, myY, 20, 20,true);
g.setColor(Color.red);
g.fillOval(nX, nY, 20, 20);
}
Coordinates of the 2 shapes are given by the user, how can i know if there's a intersection between them? (I don't need coordinates of the intersection, just need to know if there is or not)
Thanks in advance!
It heavily depends on the context and the actual intention. A very simple solution is to use the Area
class: Just create one Area
object for each of the shapes that you want to check, and intersect
these areas:
Shape shape0 = new Rectangle2D.Double(mxY, myY, 20, 20);
Shape shape1 = new Ellipse2D.Double(nX, nY, 20, 20);
Area a0 = new Area(shape0);
Area a1 = new Area(shape1);
a0.intersect(a1);
if (!a0.isEmpty()) { /* They intersect! */ }
(BTW: You can cast your Graphics
object to Graphics2D
and then paint the Shape
objects directly)
Important : Note that this solution may be very inefficient compared to an analytic solution. If you only have to check "simple" objects (circles, rectangles...) for intersection, you might want to implement an analytic solution, especially if you have to check "many" of these simple objects. The advantage of the Area
solution is its simplicity and genericity: It works for arbitrary shapes, even complex shapes like font letters or manually created Path2D
objects.