Game Development Reference
In-Depth Information
Updating
updateScene
The task
updateScene
is also updated from the preceding chapter, as shown in Listing 6-4.
Listing 6-4. GameController.m (updateScene)
-(void)updateScene{
for (Actor* actor in actors){
[actor step:self];
}
for (Actor* actor in actors){
for (NSObject<Behavior>* behavoir in [actor behaviors]){
[behavoir applyToActor:actor In:self];
}
}
for (Actor* actor in actors){
[self updateViewForActor:actor];
}
[self doAddActors];
[self doRemoveActors];
stepNumber++;
}
In this listing, we iterate over all of the actors in the game three times. In the first loop, we call
step
:
on each actor, giving it a chance to apply any custom code. In the second loop, we apply each
Behavior
associated with the actor.
Behavior
is a protocol that describes some shared behavior
among actors (this protocol is defined in
Actor.h
, shown later in Listing 6-9). In the third loop, we
update the
UIView
representing each actor by calling
updateViewForActor
:.
Because actors and behaviors are free to add or remove other actors and we don't want to modify
the
NSMutableSet
actors while we are iterating over that same collection, we have to add and
remove actors in two steps. To implement this two-step process, we store newly added actors in the
NSMutableSet actorsToBeAdded
and then process each actor in that array in the task
doAddActors
.
We follow an identical pattern for actors to be removed, storing them in the
NSMutableSet
actorsToBeRemoved
and then processing them in the task
doRemoveActors
.
Calling
doAddActors
and
doRemoveActors
The last step we take in
updateScene
is to call
doAddActors
and
doRemoveActors
, as shown in
Listing 6-5.
Listing 6-5. GameController.m (doAddActors and doRemoveActors)
-(void)doAddActors{
for (Actor* actor in actorsToBeAdded){
[actors addObject:actor];
UIView* view = [[actor representation] getViewForActor:actor In:self];
[view setFrame:CGRectMake(0, 0, 0, 0)];
[actorsView addSubview:view];