Hi,
I can't figure how to detect collision between Ellipse2D and Rectangle2D. I have tried intersects and contains methods with and without getBounds and getBounds2D methods but nothing works.
Here is some code, ball and bat are overlapped.
package net.viped;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Ellipse2D.Double;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Board2d extends JPanel {
private boolean left = false;
private boolean right = false;
private boolean up = false;
private boolean down = false;
private boolean gameOn = true;
double batx = 10.0;
double baty = 0.0;
double ballx = 10.0;
double bally = 0.0;
int tx = 0;
int ty = 0;
Ellipse2D ball = new Ellipse2D.Double(ballx, bally, 10, 10);
Rectangle2D playerBat = new Rectangle2D.Double(batx, baty, 10.0, 50.0);
AffineTransform at = new AffineTransform();
gameThread gt = new gameThread();
public Board2d() {
setFocusable(true);
addKeyListener(new ListenKeys());
setBackground(Color.black);
initGame();
gt.start();
}
public void initGame() {
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.green);
g2d.setTransform(at);
g2d.fill(ball);
g2d.setTransform(at);
g2d.translate(tx, ty);
g2d.fill(playerBat);
}
public class gameThread extends Thread {
public void run() {
while (gameOn) {
try {
sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (down) {
ty++;
}
if (up) {
ty--;
}
if (ball.getBounds2D().contains(playerBat.getBounds2D())) {
System.out.println("osuma");
}
System.out.println(ball.getBounds2D());
System.out.println(playerBat.getBounds2D());
// System.out.println(batx + ", " +baty);
repaint();
}
}
}
public class ListenKeys extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
}
public void keyReleased(KeyEvent e) {
up = false;
down = false;
}
}
}