0

I need to detect collision between one ball(oval) and many blocks(rectangles). In class Block which represent block in the game, I have following code to detect collision (its short version, just for show example):

    if(ballYPos <= blockYPos 
         && ballYPos >= blockYPos 
         && ballXPos >= blockXPos
         && ballXPos+ballWidth <= blockXPos+blockWidth) {
   collision
   }

collisions are not good, because of oval, but generally, I want to ask if there is something in java(swing) to detect collisions, I mean something like if rectangle is not fully showed on Canvas which means the ball is overlapping a block coordinates

SantiBailors
  • 1,596
  • 3
  • 21
  • 44
  • i think you need to make your own algorithm to catch the collision. i.e. logic – Keerthivasan Nov 29 '13 at 12:32
  • @KeerthiRamanathan is right, you will have to implement the logic by yourself, there might be frameworks out there that have it, but you will have to find that for yourself (finding libraries / tools is offtopic on SO. I will flag the question as the core question is off topic (is there a framework?), you have gotten short answers here in the comments – LionC Nov 29 '13 at 12:38
  • See [this answer](http://stackoverflow.com/a/14575043/418556) for a solution which leverages the power of Java-2D. – Andrew Thompson Nov 29 '13 at 14:12

2 Answers2

3

The method Shape.intersects() can be used to determine if a shape intersects with any rectangle. Luckily, it is possible to use that also with non-rectangular shapes, such as ellipses. Here is an example:

public class IntersectExample extends JFrame {
    public IntersectExample() {
        add(new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Shape oval = new Ellipse2D.Double(10, 10, 200, 200);
                Shape rect = new Rectangle2D.Double(190, 190, 200, 200);
                Graphics2D g2 = (Graphics2D) g;
                g2.draw(oval);
                g2.draw(rect);
                System.out.println(oval.intersects(rect.getBounds()));
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 400);
            }
        });
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
    }

    public static void main(String[] args) {
        new IntersectExample().setVisible(true);
    }
}

It looks like this ...

enter image description here

... and prints false to console. That shows, that not just the bounding rectangles are compared, but the actual shape area.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
0

The class java.awt.Rectangle has an intersects method(Rectangle r) which returns true when two rectangles occupy the same space (source). I guess you could adapt it to your needs.