创建从不与java重叠的图形对象

时间:2013-05-21 09:36:05

标签: java arrays object

我正在java中制作一个小型气球游戏并尝试编写我的代码,这样当我创建新的“气球”对象时,它们就不会在屏幕上重叠。

我到目前为止的代码是:

 public void newGame(){
    UI.clearGraphics();
    this.currentScore = 0;
    this.totalPopped = 0;
    for (int i = 0; i < this.balloons.length-1; i++) {
        this.balloons[i] = new Balloon(50 + Math.random()*400, 50 + Math.random()*400);
        for (int j = i + 1; j < this.balloons.length; j++) {
            if (this.balloons[i] !=null && this.balloons[j] != null && this.balloons[i].isTouching(balloons[j])) {
                this.balloons[j] = new Balloon(50 + Math.random()*400, 50+ Math.random()*400);
            }
        }
        this.balloons[i].draw();
    }
    UI.printMessage("New game: click on a balloon.  High score = "+this.highScore);
}

使用draw和isTouching方法:

    public void draw(){
    UI.setColor(color);
    UI.fillOval(centerX-radius, centerY-radius, radius*2, radius*2);
    if (!this.popped){
        UI.setColor(Color.black);
        UI.drawOval(centerX-radius, centerY-radius, radius*2, radius*2);
    }
}

    /** Returns true if this Balloon is touching the other balloon, and false otherwise
 *  Returns false if either balloon is popped. */
public boolean isTouching(Balloon other){
    if (this.popped || other.popped) return false;
    double dx = other.centerX - this.centerX;
    double dy = other.centerY - this.centerY;
    double dist = other.radius + this.radius;
    return (Math.hypot(dx,dy) < dist);
}

我怎么写这个,所以当创建气球时,它们都没有相互接触?

1 个答案:

答案 0 :(得分:1)

现在你有两个循环。在第一个循环中创建气球。在第二个循环中,每个气球都针对每个其他循环进行测试。在第一个循环中进行此测试:在创建新气球后,针对所有现有气球进行测试。