When I am working with cocos2d I can add CCSprites to the layer or 'stage' and manipulate them.

Now, to do my ongoing calculations for movement AI and such, things that will always run, should I:

subclass CCSprites and add methods to manipulate themselves and run schedules?


create a controller class that 'owns' all of the CCSprites and manipulate them from the 'outside'? I am not really sure what would be accessible from the outside though.

My guess is that I should probably subclass the CCSprite object, I could have a different object that inherits from CCSprite for each type of sprite needed.

Player, Enemy, PowerUp, Bullet, etc...

Or what do you think?


1 Answer 1


It's often better to prefer composition to inheritance.

In this specific case, I would strongly advise against using inheritance to arrive at a solution. What you are trying to do is take a sprite, which is naturally a rendering entity, and inject into it some methods and data for handling responsibilities outside its domain -- namely what sounds like AI and pathfinding. This is violating the single responsibility principle.

A far superior solution would be to have some kind of object (for things dealing with AI and scheduling, such objects are often called "actors") that contains a pointer or reference to a sprite and manipulates that sprite as-needed based on its own logic. This sounds more similar to your second, "controller" type approach.

However I would also advise, along the same lines, against creating a subclass of this controller type for each classification of actor (player, enemy, bullet). The behavior of those different types of controllers tend to differ in data, not in code, so there's little reason to create a complex inheritance hierarchy where no hierarchy is required at all. The differences between a player and a bullet are probably all things that can be altered by altering properties of the controller or sprite -- the image used, its bounded, and perhaps the name of the script that controls motion behavior.

  • \$\begingroup\$ So then, I write a class that will be instantiated by the Layer or Director and it would have access to the Layer(s) and be able to add, remove, update, the Sprites? If I am creating custom actions for the Sprites, do those get written in this Controller object or will I still need to subclass the Sprite? \$\endgroup\$
    – MetaGuru
    Commented May 22, 2011 at 23:03
  • \$\begingroup\$ "Layer" and "Director" don't mean anything to me (they don't communicate their function well through their name alone). I would expect custom actions to be handled by the controller class though -- possibly by the controller holding on to a reference to a script (or some script-like object). You shouldn't need to subclass the sprite for any of this. \$\endgroup\$
    – user1430
    Commented May 23, 2011 at 14:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .