Collisions

Making THE OCTOBER GAME: Collision History

As I’ve worked on game prototypes over the last year, I learned several methods of detecting collisions.

Touch in UIView

All native Cocoa Touch (iPhone) widgets detect touches using some private method.

Point-in-rectangle

A built in function of Core Graphics, good for detecting collisions of abstract objects where one is vanishingly small.

Rectangle-intersects-rectangle

Another built-in function of Core Graphics. You give it two CGRects and it returns a YES if they intersect. Finds collisions between two extended objects. Not so great with images that don’t fill out their bounding rectangles.

Circle-in-circle

Easy to implement with a bit of algebra. As one of the circle radii shrinks to zero, it reduces to point-in-circle so you don’t have to duplicate code. Performance is surprisingly good even without obvious optimizations.

You can Google for many, many other methods if you need better performance or versatility.

My game entities have a few properties that make collision detection simple:

  • There are only a few of them interacting
  • They don’t move very fast each timestep
  • They have simple, compact shapes that approximate circles
  • Don’t need to calculate bouncing, momentum or deflection angles

That wasn’t luck, I picked a game genre that didn’t need more advanced methods.

Here’s the code I used:

- (BOOL) circleCenter:(CGPoint)c1 radius:(float)r1 intersectsCircleCenter:(CGPoint)c2 radius:(float)r2; {

float dx = c2.x – c1.x;

float dy = c2.y – c1.y;

float distance = sqrtf((dx * dx) + (dy * dy));

float touchingDistance = r1 + r2;

return (distance <= touchingDistance); // precisely tangent counts as a hit

}

Basically, two circles are colliding if they’re intersecting. They’re intersecting if the distance between their center points is less than the touching distance, that is, the sum of their radii.

See diagram below:

LOL Collision

This entry was posted in Objective-C, programming and tagged , , , , , . Bookmark the permalink.

Comments are closed.