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

标签 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);
}

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

最佳答案

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

关于java - 创建从不与java重叠的图形对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16666747/

相关文章:

java - 使用另一个java程序编译一个java程序

java - Jsch - 每个 session 多个 channel

java - 查找数组中任何重复的元素

arrays - 在整数数组中查找重复项

javascript - JS - Array.prototype.clone 向所有数组添加一个元素

javascript - 如何使 JavaScript 对象更具可读性/可导航性?

java - java 中的类型检查和泛型会生成警告

java - Notify()/NotifyAll() 全部在退出同步块(synchronized block)之前

javascript - 实例化每个键都等于 null 的对象的最佳方法?

java - 类对象比较 - equals 方法输出错误