Game Development Reference
In-Depth Information
In Listing 6-6, you can see two very simple tasks:
addActor
and
removeActor
. In
addActor
, the
passed-in actor has its added property set to YES before the actor is added to the
NSMutableSet
actorsToBeAdded
. Similarly, in the task
removeActor
, the passed-in actor has its removed property set
to YES and is added to the
NSMutableSet actorsToBeRemoved
.
Earlier, in Listing 6-5, when actors are added or removed from the set actors, we also added or
removed the actors from sets stored in the
NSMutableDictionary actorClassToActorSet
. This is
done so we can find all actors of a given type without iterating through the entire set actors. We
don't, however, want to keep a separate set for each type of actor in the game. We just want to keep
track of the types of actors we will need access to in the game logic.
Sorting Actors
The task
setSortedActorClasses
is used to specify which actors should be sorted, as shown in
Listing 6-7.
Listing 6-7. GameController.m (setSortedActorClasses:)
-(void)setSortedActorClasses:(NSMutableArray *)aSortedActorClasses{
[sortedActorClasses removeAllObjects];
sortedActorClasses = aSortedActorClasses;
[actorClassToActorSet removeAllObjects];
actorClassToActorSet = [NSMutableDictionary new];
for (Class class in sortedActorClasses){
[actorClassToActorSet setValue: [NSMutableSet new] forKey:[class description]];
}
for (Actor* actor in actors){
NSMutableSet* sorted = [actorClassToActorSet objectForKey:[[actor class] description]];
[sorted addObject:actor];
}
}
We start with a little memory management, removing all objects from the
NSMutableArray
sortedActorClasses
and releasing it before reassigning the
sortedActorClasses
to the
passed-in
NSMutableArray aSortedActorClasses
. Next, we clear the old
NSMutableDictionary
actorClassToActorSet
. Once the bookkeeping is done, we add a new
NSMutableSet
for each class in
sortedActorClass
to
actorClassToActorSet
. Finally, we iterate through all actors and add each one
to the corresponding
NSMutableSet
. This last step is required to allow
setSortedActorClasses
to be
called multiple times in an application, but considering this is a relatively expensive operation, it is
best to call
setSortedActorClasses
once at the beginning of the game.