I've written an objective-c routine that works well with ball-ball collisions. However, having an issue with ball-rectangle collisions, i.e. a simple barrier (not external walls).
The detection is simple, but the what happens after detection is causing the problem. A bounce off the horizontal or vertical surfaces are handled fine but when the collision occurs near the corners the ball becomes static and won't move.
In pseudo code it goes like this:
The first part handles the situation where a ball is moving fast enough to enter the rectangle before the collision check happens by moving the ball back in time to a point just before it collided. The second part performs a simple test to check if the ball is striking a the horizontal or vertical side of the rectangle and then changing the x or y component of the velocity vector as necessary.
Here is the method:
Any ideas?
The detection is simple, but the what happens after detection is causing the problem. A bounce off the horizontal or vertical surfaces are handled fine but when the collision occurs near the corners the ball becomes static and won't move.
In pseudo code it goes like this:
Code:
for (balls in ballarray)
if ball intersects barrier
reverse velocity vector
move back so not touching
reverse velocity vector (return to original vector)
if ball is hitting horizontal surface
reverse y of velocity vector
else
reverse x of velocity vector
end
end
The first part handles the situation where a ball is moving fast enough to enter the rectangle before the collision check happens by moving the ball back in time to a point just before it collided. The second part performs a simple test to check if the ball is striking a the horizontal or vertical side of the rectangle and then changing the x or y component of the velocity vector as necessary.
Here is the method:
Code:
for (Ball *aBall in ballArray){
if (CGRectIntersectsRect(aBall.getRect, barrier.position))
{
//move ball back until not touching barrier
aBall.velocity = CGPointMake(aBall.velocity.x*-1.0f, aBall.velocity.y*-1.0f);
while (CGRectIntersectsRect(barrier.position,aBall.getRect)) {
[aBall simpleUpdate];
}
//return velocity of ball to previous value
aBall.velocity = CGPointMake(aBall.velocity.x*-1.0f, aBall.velocity.y*-1.0f);
//cx is midpoint of barrier on x axis
NSInteger cx = barrier.position.origin.x+(barrier.position.size.width/2);
if (abs(aBall.position.x-cx)<(barrier.position.size.width/2)){
//must be on horzontal surface
aBall.velocity = CGPointMake(aBall.velocity.x, aBall.velocity.y*-0.9f);
} else {
//must be vertical surface
aBall.velocity = CGPointMake(aBall.velocity.x*-0.9f, aBall.velocity.y);
}
//}
}
NSLog(@"Velocity x=%f y=%f",aBall.velocity.x, aBall.velocity.y);
Any ideas?