0

我正在用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);
}

我该如何写这个,以便在创建气球时,它们都不会相互接触?

4

1 回答 1

1

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

于 2013-05-21T09:40:07.910 回答