圆碰撞检测

时间:2013-02-03 14:46:09

标签: java

我创建了一个程序,在屏幕上绘制2个圆圈,并使用键盘ASWD和箭头键移动..代码是

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("Simple Ball");

    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) {}

}

现在我需要测试碰撞。一旦两个球相互接触。它会显示一条消息“碰撞检测”..请帮助...

1 个答案:

答案 0 :(得分:2)

不是简单的:如果两个中心点的距离都小于或等于半径的总和,那么就会发生碰撞吗?