import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class HitDetection extends JPanel implements Runnable {
Rectangle[] blocks = {
new Rectangle(100,100,30,30), new Rectangle(140,160,30,30),
new Rectangle(240,270,30,30), new Rectangle(200,300,30,30)
};
Ellipse2D.Double ball = new Ellipse2D.Double(200,10,20,20);
int dx = 3;
int dy = 2;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for(int j = 0; j < blocks.length; j++)
g2.draw(blocks[j]);
g2.setPaint(Color.red);
g2.fill(ball);
}
public void run() {
boolean running = true;
while(running) {
try {
Thread.sleep(50);
} catch(InterruptedException e) {
running = false;
}
checkForCollision();
checkBoundries();
double x = ball.x + dx;
double y = ball.y + dy;
ball.setFrame(x, y, ball.width, ball.height);
repaint();
}
}
private void checkForCollision() {
Ellipse2D.Double e = new Ellipse2D.Double();
e.setFrame(ball.x+dx, ball.y+dy, ball.width, ball.height);
for(int j = 0; j < blocks.length; j++) {
if(e.intersects(blocks[j])) {
bounce(blocks[j], e);
break;
}
}
}
private void bounce(Rectangle r, Ellipse2D.Double e) {
double cx = e.getCenterX();
double cy = e.getCenterY();
int outcode = r.outcode(cx, cy);
switch(outcode) {
case Rectangle.OUT_TOP:
case Rectangle2D.OUT_BOTTOM:
dy *= -1;
break;
case Rectangle2D.OUT_TOP + Rectangle2D.OUT_LEFT:
case Rectangle2D.OUT_LEFT + Rectangle2D.OUT_BOTTOM:
case Rectangle2D.OUT_BOTTOM + Rectangle.OUT_RIGHT:
case Rectangle2D.OUT_RIGHT + Rectangle2D.OUT_TOP:
dx *= -1;
dy *= -1;
break;
case Rectangle2D.OUT_LEFT:
case Rectangle2D.OUT_RIGHT:
dx *= -1;
break;
default:
System.out.println("CENTER: " + outcode);
}
}
private void checkBoundries() {
if(ball.x + dx < 0 || ball.x + ball.width + dx > getWidth())
dx *= -1;
if(ball.y + dy < 0 || ball.y + ball.height + dy > getHeight())
dy *= -1;
}
private void start() {
while(!isVisible()) {
try {
Thread.sleep(25);
} catch(InterruptedException e) {
break;
}
}
Thread thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
public static void main(String[] args) {
HitDetection test = new HitDetection();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
test.start();
}
}