问题描述:

So I wrote this code to check for the collision between boxes.

for (var i = 0; i < boxes.length; i++) {

for (var j = 0 ; j < boxes.length; j++) {

if (i != j) {

if (boxes[i].posX + 50 >= boxes[j].posX

&& boxes[i].posX <= boxes[j].posX + 50

&& boxes[i].posY + 50 >= boxes[j].posY

&& boxes[i].posY <= boxes[j].posY + 50

) {

console.log("box" + i + "collide with box" + j);

boxes[i].movePosX *= -1;

boxes[i].movePosY *= -1;

}

}

}

}

It works for 2 to 3 boxes, but when I keep 4 or more boxes some of the boxes collide but doesnt change its direction.

can anyone help me debug this?.

Also can anyone teach me process of debugging as how I can detect the problem.

New to Javascript.

Thank you.

网友答案:
for (var i = 0; i < boxes.length; i++) {
    for (var j = 0; j < boxes.length; j++) {
        if (i != j) {
            if (!(boxes[i].posX + 50 <= boxes[j].posX
                || boxes[i].posX >=  boxes[j].posX + 50
                || boxes[i].posY + 50 <= boxes[j].posY
                || boxes[i].posY >= boxes[j].posY + 50
            )) {
                console.log("box" + i + "collide with box" + j);
                boxes[i].movePosX *= -1;
                boxes[i].movePosY *= -1;
            }
        }
    }
}

I usesed this function from: http://7pi.azurewebsites.net/surir.de/collisions/

function cc_rect_rect(r1, r2) {
    return !(r1.pos.x >= r2.pos2.x || r1.pos2.x <= r2.pos.x || r1.pos.y >= r2.pos2.y || r1.pos2.y <= r2.pos.y);
}
相关阅读:
Top