advertisement

Article:
  Animating Graphics in Cocoa, Part 1
Subject:   Faulty collision method
Date:   2003-01-24 07:05:03
From:   anonymous2
The collision method given will not handle corner-collisions correctly. If both x & y coordinates are out of the bounds, the checkCollision method will only flip the y coordinate: this is due to the use of if... else if rather than two ifs.
In most cases, this won't be a problem, as most collisions will not occur at the corners. However, if the collision does occur at a corner, only delta y will be flipped.
This will result in the x-coordinate of the ball to be outside the intended display bounds. Because the x-coordinate is incremented even though it should have been flipped, the ball is moved further from the intended view area. After this, the ball's x position will be stuck until the next y-collision, (or possibly longer) which is not the desired effect.


New version:
- (void)checkCollision
{
NSRect ballRect = [ball bounds];
NSRect viewRect = [self bounds];


BOOL flipY = ( ballRect.origin.y < viewRect.origin.y || (ballRect.origin.y + ballRect.size.height) > viewRect.size.height );
BOOL flipX = ( ballRect.origin.x < viewRect.origin.x || (ballRect.origin.x + ballRect.size.width) > viewRect.size.width );

if ( flipY || flipX ) { //If we need to flip one of the coords,
[at release];
at = [[NSAffineTransform transform] retain];


if ( flipY ) //Flip coordinates as needed.
dy = -dy;
if ( flipX )
dx = -dx;


[at translateXBy:dx yBy:dy];
}
}


(Think that one will work.... Still, if the view is resized and the ball is outside of the new bounds, it'll stay out there.)


Of course, this is a simple tutorial, and it's not really important. But I though I'd point it out.


Peace, Nicholas Seckar