我认为进行一些重构是有必要的。以下内容可能有助于为您指明正确的方向:
注意:我没有验证代码,所以请阅读每个字符。另外,我认为左右已设置,但没有通过顶部/底部或最终移动逻辑,因为我认为我不理解原始逻辑(或者至少它开始对我没有意义- 似乎您在某处缺少||)。
this.ballCollide = function() {
for (var i = 0; i < ball.length; i++) {
var ax = ballX[i];
var ay = ballY[i];
for (var j = i + 1; j < ball.length; j++) {
var bx = ballX[j];
var by = ballY[j];
var left = ( ax <= bx + 50 );
var right = ( ax + 50 >= bx );
var top = ( ay + 50 >= by );
var bottom = ( ay <= by + 50 );
if( (left && right) && (top && bottom) ){
movePosX[i] = -movePosX[i];
movePosY[i] = -movePosY[i];
movePosX[j] = -movePosX[j];
movePosY[j] = -movePosY[j];
}
}
}
}
这是一个可能有用的“包含”功能:
function contains (big, small){
if( ! big || ! small ){
return false;
}
var Oresult = {};
var Obig = {x:big.x, y:big.y, w:big.width, h:big.height};
var Osmall = {x:small.x, y:small.y, w:small.width, h:small.height};
Obig.xMax = Obig.x + Obig.w;
Obig.yMax = Obig.y + Obig.h;
Osmall.xMax = Osmall.x + Osmall.w;
Osmall.yMax = Osmall.y + Osmall.h;
for (var p in Obig) {
Oresult[p] = ( Obig[p] >= Osmall[p] ) ? true : false;
}
var retval = (!Oresult.x && !Oresult.y && Oresult.xMax && Oresult.yMax) ? true : false;
return retval;
}