Game Development Reference
In-Depth Information
In Listing 5-16, we see the task updateScene , the heartbeat of the game, it gets called about 60
times a second and is where we advance the game along. The first thing we do is check to see if we
want to add a new asteroid to the game. This is done by taking stepNumber and moding it by 600
and seeing if the value is zero. In effect, this adds a new Asteroid02 to the scene every 10 seconds,
since the game is running at about 60 frames a second.
After testing if a new asteroid should be added, we iterate through all of the actors in the game
and call step: on them. This gives each actor a chance to advance its state based on its particular
behavior. The background will do nothing, the asteroids will move downward, and the spaceship
will move toward its moveToPoint . After updating the location of each actor, we want to test to see if
there was a collision. This is done by again iterating through all of the actors, finding the ones that
are asteroids, and checking for a collision state. For this simple example, iterating over all of the
actors to find a collision is okay. However, in a more complex application, it is probably important to
improve this algorithm (such as it is). Improvements can include keeping track of all asteroids in their
own array and possibly sorting them by location.
Updating the UIView for Each Actor
We have tested if there were any collisions, and now we have to figure out the new location of each
actor's UIImageView . This is done in the updateActorView: task, as shown in Listing 5-17.
Listing 5-17. Example02Controller.m (updateActorView:)
-(void)updateActorView:(Actor02*)actor{
UIImageView* imageView = [actorViews objectForKey:[actor actorId]];
if (imageView == nil){
UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:[actor imageName]]];
[actorViews setObject:imageView forKey:[actor actorId]];
[imageView setFrame:CGRectMake(0, 0, 0, 0)];
[actorView addSubview:imageView];
}
float xFactor = actorView.frame.size.width/self.gameAreaSize.width;
float yFactor = actorView.frame.size.height/self.gameAreaSize.height;
float x = (actor.center.x-actor.radius)*xFactor;
float y = (actor.center.y-actor.radius)*yFactor;
float width = actor.radius*xFactor*2;
float height = actor.radius*yFactor*2;
CGRect frame = CGRectMake(x, y, width, height);
[imageView setFrame:frame];
}
In Listing 5-17, the first thing we do is find which UIImageView is representing the actor that was
passed in. We find it by looking up the UIImageView in the NSMutableArray actorViews , using the
actor's actorId as the key. If we don't find a UIImageView , then this actor must have just been added,
so we have to create it.
 
Search WWH ::




Custom Search