Try this:
collisionCheck: function(bArray){
for(var i=0,len=bArray.length; i<len; ++i){
for(var j=0,len2=bArray[i].length; j<len2; ++j){
if(!bArray[i][j].getType()) continue;
var x = bArray[i][j].getX(), y = bArray[i][j].getY();
var x2 = x+blockSize, y2 = y+blockSize;
var overlapping = (x2>this.x) && (x<(this.x+this.width)) && (y2>this.y) && (y<(this.y+this.height));
if (overlapping) this.x = 0; // I don't know why you'd do this, but it's what you have
}
}
// Should this function return anything?
}
To answer your question as to why your current logic is not correct, let's focus on one problem. Your logic says basically that there is a collision if:
(YourLeftEdgeIsPastMyLeftEdge AND YourLeftEdgeIsNotPastMyRightEdge)
OR
((Something AND Something) AND (Something AND Something))
OR
(Something AND Something)
The middle line is because && has higher precedence than ||, causing the middle two lines of your condition to be clumped together.
Looking that that, we can see that a the collision can succeed by checking only the horizontal placement of the two items, which is clearly a mistake.
The logic I have in my answer is basically that two objects do not overlap if:
- A. The right edge of one is to the left of the left edge of the other, OR
- B. The left edge of one is to the right of the right edge of the other, OR
- C. The bottom edge of one is above the top edge of the other, OR
- D. The top edge of one is below the bottom edge of the other.
De Morgan's Laws say that !(A || B || C || D) is the same as (!A && !B && !C && !D), and so we can say that two objects do overlap if:
- A. The right edge of one is to the right of the left edge of the other, AND
- B. The left edge of one is to the left of the right edge of the other, AND
- C. The bottom edge of one is below the top edge of the other, AND
- D. The top edge of one is above the bottom edge of the other.
And this results in the code I supplied:
(x2>this.x) && (x<(this.x+this.width)) && (y2>this.y) && (y<(this.y+this.height))