我创建了一个java程序来绘制2个圆圈并使用键盘移动..我需要测试碰撞...一旦两个球一起移动..它会弹出消息“碰撞检测到”
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BallObject {
private int x;
private int y;
private int radius;
BallObject() {
x=0;
y=0;
radius=0;
}
BallObject (int x,int y,int radius) {
this.x=x;
this.y=y;
this.radius=radius;
}
public void setX(int x) {this.x=x;}
public void setY(int y) {this.y=y;}
public void setRadius(int r) {radius=r;}
public int getX() {return x;}
public int getY() {return y;}
public int getRadius() {return radius;}
}
class Ball extends JFrame implements KeyListener {
BallObject ball1;
BallObject ball2;
Ball() {
super("COLLISION DETECTION BETWEEN TWO BALLS");
setSize(800,600); //set screen resolution
ball1 = new BallObject(getWidth()/2,getHeight()/2,20);
ball2 = new BallObject(40,40,20);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fill(new Rectangle(0,0,800,600));
//drawing ball1
g2d.setColor(Color.RED);
g2d.fillOval(ball1.getX(),ball1.getY(),ball1.getRadius()*2,ball1.getRadius()*2);
//drawing ball2
g2d.setColor(Color.GREEN);
g2d.fillOval(ball2.getX(),ball2.getY(),ball2.getRadius()*2,ball2.getRadius()*2);
}
public static void main (String args[]) {
new Ball();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT)
ball1.setX(ball1.getX()-2);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
ball1.setX(ball1.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_UP)
ball1.setY(ball1.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_DOWN)
ball1.setY(ball1.getY()+2);
if(e.getKeyCode()==KeyEvent.VK_A){
ball2.setX(ball2.getX()-2);
//System.out.println("Hello");
}
if(e.getKeyCode()==KeyEvent.VK_D)
ball2.setX(ball2.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_W)
ball2.setY(ball2.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_S)
ball2.setY(ball2.getY()+2);
repaint();
}
//redraw the screen to show the updated ball location
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
所以现在我想测试两个圆圈之间的碰撞..
if (((ball2.getX()-ball1.getX())* (ball2.getX()-ball1.getX())) + ((ball2.getY()-ball1.getY())* (ball2.getY()-ball1.getY()))
< ball1.getRadius() + ball2.getRadius()* ball1.getRadius() + ball2.getRadius() );
{
System.out.println("The 2 circles are colliding!");
}
}
但程序无法正常工作..请帮助..
答案 0 :(得分:4)
1)为什么你有ball2.getRadius()* ball1.getRadius()
这个词? (R1 + R2)*(R1 + R2)
应该是两者之间距离的平方。
2)请清理代码..
int dX = ball2.getRadius()* ball1.getRadius(), dY = ball2.getY()-ball1.getY();
int R = ball1.getRadius() + ball2.getRadius();
if( (dX*dX +dY*dY) < R*R){
或将所有这些转移到成员函数中。
if( ball2.distanceSquared(ball1) <R*R){
或
if(ball2.collide(ball1)){