Game Development Reference
In-Depth Information
Subclassing Game Objects from CCS-
prite
Very often your game objects implement logic of their own. It makes sense to create a
separate class for each type of game object. This could be your player character, vari-
ous enemy types, bullets, missiles, platforms, and just about everything else that can be
individually placed in a game's scene and needs to run logic of its own.
The question then is, where to subclass from?
A lot of developers choose the seemingly obvious route of subclassing CCSprite . I
don't think that's a good idea. The relationship of subclassing is a “is a” relationship.
Think closely: is your player character a CCSprite ? Are all your enemy characters
CCSprite s?
At first the answer seems logical: of course they're sprites! That's what they use to dis-
play themselves. But wait a second. For all we know, game characters can also be char-
acters in the literal sense. In Rogue-like games, your player character is an @. So,
would that character be a CCLabelTTF then?
I think the confusion comes from CCSprite being the most widely used class to dis-
play anything onscreen. But the true relationship of your game characters to CCNode
classes is a “has a” relationship. Your player class “has a” CCSprite that it uses to
display itself, and it may even have to use multiple sprites for weapons, armor, and so
on—and maybe even particle effects for running at high speed, a health bar, and a label
to display the player's name in multiplayer modes.
The distinction becomes even clearer when you think of why you'd normally subclass
the CCSprite class: in general, to add new features to the CCSprite class—for ex-
ample, to have a CCSprite class that uses a CCRenderTexture to modify how it's
displayed based on what's beneath it on the screen. Essentially you'd want to subclass
CCSprite to change the behavior of the CCSprite class itself and how the sprite is
displayed—not to add gameplay code to it.
Input handling, animating the player, collision detection, physics—in general, game lo-
gic. None of these things belongs to a CCSprite class because this code is about how
an object behaves and how you interact with it, not how a sprite is drawn on the screen.
Search Nedrilad ::




Custom Search