Game Development Reference
In-Depth Information
Another way to look at it is to consider which of the code you add to a subclassed
CCSprite is generally useful and usable by all sprites. Most game code is very spe-
cific to an individual game object, be it player, boss monster, or collectible item.
Consider the case where you want your player to have several visual representations
that it should be able to switch to seamlessly. If the player needs to morph from one
sprite to another using FadeIn / FadeOut actions, you're going to have to use two
sprites—or if you want your game objects to appear on different parts of the screen at
the same time, as in a game like Asteroids where the asteroid leaving the top of the
screen should also show up partially at the bottom of the screen. You need two sprites
to do this, and that's just one reason why composition (or aggregation) is preferable to
subclassing (or inheritance). Inheritance causes tight coupling between classes, with
changes to parent classes potentially introducing bugs and anomalies in subclasses. The
deeper the class hierarchy, the more code will reside in base classes, which amplifies
the problem.
Another good reason is that a game object encapsulates its visual representation. If the
logic is self-contained, only the game object itself should ever change any of the
CCNode properties, such as position, scale, rotation, or even running and stopping ac-
tions. One of the core problems many game developers face sooner or later is that their
game objects are directly manipulated by outside influences. For example, you may in-
advertently create situations where the scene's layer, the user interface, and the player
object itself all change the player sprite's position. This is undesirable. You want all the
other systems to notify the player object to change its position, giving the player object
itself the final say about how to interpret these commands—whether to apply them,
modify them, or ignore them.
Composing Game Objects Using CCS-
prite
Let's try this. Instead of creating a new class derived from a CCSprite class, create it
from cocos2d's base class CCNode . Although you can also base your class on the
Objective-C base class NSObject , it's easier to stick to CCNode because it's gener-
ally easier to work with CCNode as your base class within cocos2d. Otherwise you
can't use convenience features like CCNode 's scheduling methods.
Search Nedrilad ::




Custom Search