【问题标题】:Checking collision for each cube in ArrayList检查 ArrayList 中每个立方体的碰撞
【发布时间】:2019-05-22 08:19:03
【问题描述】:

我正在尝试检查 arraylist 中每个立方体的碰撞,但结果是,该碰撞仅适用于 arraylist 中的最后一个立方体..

public class Cube {

    public int x, y;
    private boolean conflict = false;

    public Cube(int x, int y) {
      this.x = x;
      this.y = y;
    }

    public void moveDown() {
        if(!conflict("down")) {
            this.y += 18;
        }
    }

    public boolean conflict(String dir) {
        if(dir.equals("down")) {
            for(Cube cubes : Panel.cubes) {
                if(this.hashCode() != cubes.hashCode()) {
                    if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
                        this.conflict = true;
                    } else this.conflict = false;
                }
            }
        }
    }
}

【问题讨论】:

    标签: java arraylist foreach


    【解决方案1】:

    首先你的冲突方法没有return 任何东西,我想知道它是如何编译的。但问题是当你发现碰撞时你永远不会出去for loop

    public boolean conflict(String dir) {
        if (dir.equals("down")) {
            for(Cube cubes : Panel.cubes) {
                if(this.hashCode() != cubes.hashCode()) {
                    if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
                        this.conflict = true;
                        break;
                    } else {
                        this.conflict = false;
                    }
                }
            }
        }
    
        return this.conflict;
    }
    

    【讨论】:

    • 谢谢它的作品! :)) 我忘记从我的代码中复制返回,但它就在那里:P
    • @mcfly24 不客气 :) 不要忘记将答案之一作为答案
    【解决方案2】:

    当您发现冲突时,您似乎想从循环中中断,否则下一次迭代可能会重置该标志(这解释了为什么“冲突仅适用于 arraylist 中的最后一个立方体”)。

        if (dir.equals("down")) {
            for(Cube cubes : Panel.cubes) {
                if(this.hashCode() != cubes.hashCode()) {
                    if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
                        this.conflict = true;
                        break;
                    } else {
                        this.conflict = false;
                    }
                }
            }
        }
    

    顺便说一句,您的 conflict 方法似乎缺少返回语句。

    【讨论】:

    • @Lino 好吧,由于原始代码中缺少 return 语句,我不想​​做任何假设。可能实际方法已更改为 void 方法(仅更新 this.conflict 而不是返回布尔值)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多