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

创建从不与java重叠的图形对象,java,arrays,object,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

我正在用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);
}
public void newGame(){
UI.clearGraphics();
此.currentScore=0;
this.totalPopped=0;
for(int i=0;i
使用draw和iTouch方法:

    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);
}
public void draw(){
UI.setColor(颜色);
UI.圆角(中心半径、中心半径、半径*2、半径*2);
如果(!this.popped){
UI.setColor(Color.black);
UI.Draw椭圆形(中心半径、中心半径、半径*2、半径*2);
}
}
/**如果此引出序号与其他引出序号相接触,则返回true,否则返回false
*如果任一气球弹出,则返回false*/
公共布尔值IsTouch(引出序号其他){
如果(this.popped | | other.popped)返回false;
double dx=other.centerX-this.centerX;
double dy=other.centerY-this.centerY;
双距离=其他半径+此半径;
返回值(数学形差(dx,dy)

我如何写这篇文章,这样在创建引出序号时,它们都不会相互接触?

现在有两个循环。在第一个循环中创建引出序号。在第二个循环中,每个气球与其他每个循环进行测试。在第一个循环中执行此测试:创建新气球后,对照所有现有气球进行测试。

您可以简单地计算气球的边界矩形,并使用“相交”方法确定它们是否重叠。我考虑过这一点,但认为它不起作用,当只创建了一个引出序号时,如何为循环的第一次迭代编写代码?当只创建了一个引出序号时,没有其他引出序号可以对其进行测试。因此,一个简单的
if
子句应该处理这种情况。。正确吗?我现在面临的问题是,在整个for循环中,至少有一个索引是空的,我如何解决这个问题?一个
int
怎么可能是
null
。它可以是
0
,但这是一个完全合法的数组索引。