the_critic
the_critic

Reputation: 12820

Use CCLayer or CCSprite class for my sprites?

I have some sprites that I do not know what class to subclass from. I currently do it with CCLayer because I can keep all the children that I have to add to the sprite in its class, however touch events are detected by all overlapping layers and that might not be so clever. So in layman terms, I want to have a flame thrower for instance where I have to add a flame when I touch it. I do that by just adding the flame within the FlameThrower.h class (which sub classes CCLayer. If I were to subclass CCSprite, I would have to add the flame in my parent's class which is ineffective as well, right ? So, what is the right approach here ?

Upvotes: 0

Views: 724

Answers (1)

Jim Range
Jim Range

Reputation: 523

You might not need to be subclasssing CCSprite or CCLayer at all.

This is a fundamental Cocos2d game architecture issue that I wish would be discussed more often.

For the games that I have created, I use NSObject or CCNode as the base class for creating characters.

These character controller classes run the logic for the AI of the character, own the physics bodies for the character if it has physics, and control one or more sprites that represent the character.

If the character controller will not require properties or functionality provided by a CCNode, then I subclass NSObject, which usually is the case for physics based characters.

User input is usually owned by a HUD, but sometimes you will want to add it directly to specific character in the game world. In that case you might want to subclass a CCLayer to add touch and accelerometer or subclasss a CCNode and register with the touch dispatcher.

Usually I create the sprites for a character in a separate class that is then created and owned by the character controller.

The games I create usually have between one and four sprite sheets and I have a GameManager class load these as CCSpriteBatchNodes and into the CCSpriteFrameCache and then when the characters are created via a world building scripting engine I pass a reference to the needed CCSpriteBatchNode to that character so that it can use the batch node to add the characters sprites to it.

Characters then register with the GameManager or a parant character to be updated, managed, and eventually destroyed and cleaned up.

For physics based characters there usually isn't even a need to subclass CCNode (much less a CCLayer or CCSprite) unless you want the physics body to control the behavior of the node directly instead of controlling the sprites that the node or NSObject would own.

Upvotes: 1

Related Questions