Cocos2D - Detect how many items an object collided with / negating more than one object

In creating a small breakout clone, I've managed to get the ball to bounce whenever it hits a block by negating (or multiplying by -1) either the X or the Y values.

This works, at least until the ball (which is really a small rect with a sprite) manages to hit two blocks at once, at which point either the X or Y values are negated twice.

The ball then proceeds to continue on its path without bouncing, resulting in a very short and very strange Breakout game.

Is there any way to detect how many items have collided with the ball, and to disregard one?

Or is there some other way to do this?

Thanks.

Here's my collision code:

if (Tools.rectsIntersect(this, g_Ball)) {
if (g_Ball.y < this.y || g_Ball.y > this.y) {
g_Ball.yDirection = g_Ball.yDirection * -1;
}
else if (g_Ball.x < this.x || g_Ball.x > this.x) {
g_Ball.xDirection = g_Ball.xDirection * -1;
}
this.destroyBlock();
}

Tools.rectsIntersect = function (obj1, obj2) {box
var aRect = obj1.collideRect();
var bRect = obj2.collideRect();
return cc.rectIntersectsRect(aRect, bRect);
};

• You're in for a bumpy ride. I'm doing the exact same thing right now. You will need to calculate the balls entire path and all its collisions in each frame because from frame 1 to frame 2 it could have hit 2 or 3 or even 4 bricks (or more) and if it is only trying to react to them after the new frame is rendered, it will find itself somewhere it shouldn't have gone. So during one game tick, you should calculate and track each brick it hits, and what point it hit the brick at. Not an easy feat. Just thought I'd enlighten you to what I've recently discovered – Neal Davis Sep 22 '16 at 16:56
• I don't even know how to do that (I'm assuming somewhere in the update of the Gamelayer), but thanks for the heads up. – zack_falcon Sep 23 '16 at 2:21
• So, if you don't want to go down that road you can do this: make the bricks far enough apart that 2 collisions can't occur during one game tick. That will be done by limiting the speed of the ball and not having no the bricks too close. You could still come up with a fun game and completely side step this issue. – Neal Davis Sep 23 '16 at 2:40
• I thought of a new solution you could pursue. First detect exactly where on the brick the ball collided, then place the ball directly at that point at the beginning of the next frame. The only actual downside here is minor. It means that the ball, if moving very fast, fast enough to hit two blocks in one game tick, it will just hit one per frame at the most. That should actually be fine though and probably not even be a noticeable slow down. – Neal Davis Sep 24 '16 at 18:22