Getting unblocked

Who doesn’t love writing games? Only people who don’t know it, IMHO.

I was recently working on a simple sprite-based game to run on iOS (for reasons which should become clear at some point), and was having fun creating classes for aliens, explosions and lasers.

Sprite-base game

Eventually I had the laser class working fine, blowing up flying saucers, but I wanted to trigger an big bang  from the explosion class at the correct location.

As all my sprite classes were quite separate, it seemed messy to pass around all the details required to trigger an explosion at the right co-ordinates, and so I wrote some Block-based code to do it. This made me happy, as Blocks – and in particular the syntax for Blocks – always seem a little like black magic to me.

Here is the method that needed calling to trigger the explosion:

-(void)explodeAt: (CGPoint) p
[explosions explode:p :_baseEffect];

Here, _baseEffect is the property that is required for the sprite rendering so don’t worry about that, but p is the location where the explosion should happen and that is important. I needed to call this method from the code that did the collision testing between the alien bad guys and the lasers. Here is how I passed that method into the testing code:

// Check for collisions between lasers and UFOs
[badguys CollisionTestAndExplode: [lasers getAllLasers] : ^void (CGPoint p) { [self explodeAt : p]; }];

Over in the lasers class, here is how that CollisionTestAndExplode method works and how it calls the explodeAt method:

// The array of sprites is provided, and checked against the UFO array.
// If there is a collection, the object is deleted, and explosion triggered

-(bool)CollisionTestAndExplode: (NSMutableArray *) targetSprites : (void (^)(CGPoint p))explodeAt
bool collision = false;
NSMutableArray *destroyed = [NSMutableArray array];
for (SpriteClass *s in targetSprites)
for (Ufo *u in _ufos)
if (CGRectIntersectsRect( [u getRect] , [s getRect] ))
[destroyed addObject:u];
collision = true;

It’s one of those things that looks very simple in retrospect, but at the time takes about an hour of trial and error get to sorted. In other words, this blog posting is my victory nerd dance and memorandum all in one.

Comments (0)

Skip to main content