Game Development Reference
In-Depth Information
I decided to turn the spiders in the ScenesAndLayers02 project into a class of their
own. The class is simply called Spider . Listing 5-11 reveals the Spider class's
header file.
Listing 5-11. The Spider Class Interface
#import "cocos2d.h"
@interface Spider : CCNode
CCSprite* spiderSprite;
int numUpdates;
+(id) spiderWithParentNode:(CCNode*)parentNode;
-(id) initWithParentNode:(CCNode*)parentNode;
You can see that the CCSprite is added as a member variable to the class and is
named spiderSprite . This is called composition because you compose the
Spider class of a CCSprite used to display it and later, possibly, other objects (in-
cluding additional CCSprite classes) and variables.
The Spider class in Listing 5-12 has a spiderWithParentNode class method to
create an instance of the Spider class. Another convenient feature I added is to pass a
parentNode as a parameter to the initWithParentNode method. By doing that,
the Spider class can add itself to the node hierarchy by calling [parentNode ad-
dChild:self] , which makes creating an instance of a Spider class a one-liner in
GameLayer.m because you only need to write [Spider spiderWithParen-
tNode:self] .
On the other hand, the spiderSprite should be self-contained because it's created
and managed by the Spider class. The spiderSprite is added via [self ad-
dChild:spiderSprite] to the Spider class and not the parentNode . Al-
though you could do that, I don't recommend it because it breaks encapsulation. For
one, the parentNode code could possibly remove the spiderSprite from its
Search Nedrilad ::

Custom Search