0

I want to implement a collision detection mechanism that detects a collision between two ovals. I'm using Java Graphics to draw ovals and I want to check whether they overlap. Is there a way to do it?

Sample ovals:

drawOval(x, y, 24, 24);
drawOval(x, y, 100, 142);

drawOval(x,y,width,height) - Java Graphics function x - the x coordinate of the upper left corner of the oval to be drawn. y - the y coordinate of the upper left corner of the oval to be drawn. width - the width of the oval to be drawn. height - the height of the oval to be drawn.

1 Answers1

1

Just drawing ovals won't help you, and instead you need to use an object that has more heft to it, more internal data and behaviors that will allow you to do these queries. Fortunately, such a type of object exists in the Graphcs2D libraries: the Shape interface and its subtypes, here Ellipse2D. Create an Ellipse2D object and then you can draw it using Graphics2D g2d.draw(myEllipse) and check for intersection using the .intersects(...) method.

e.g.,

// declare and initialize fields
private int x = 0;
private int y = 0;
private Ellipse2D myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
private Ellipse2D myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);
// draw your shapes in the drawing JPanel
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    // change the g2d's color?
    g2d.draw(myEllipse1);

    // change the g2d's color?
    g2d.draw(myEllipse2);

    // ...
}

elsewhere, such as in a Swing Timer's ActionListener:

// set location values to proper value
x = somethingNew;
y = somethingElseNew;

// create new Ellipse2D objects based on the x,y changes
myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);

// test for intersection
if (myEllipse1.intersects(myEllipse2) {
    // do something
}

// ask the GUI to re-draw itself
repaint();
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373