About
To Components with Cocos2D with love…
Components are being used in most modern game engines. My favorite (because of it makes sense to me is the PushButton Game Framework). I like the design behind it. So when faced with developing a game using Cocos2D, I tried figuring out how to approach it architecturally.
Cocos2D is a fairly mature framework and you might as why put something on top of that. I had the choice between choosing a Model View Controller Architecture and a Component (Composition Approach). I chose Components easily. I’ve only been working with the framework for a few days but I have already got that “wow” that makes more sense now feeling.
For example, here is some code to add a entity with a sprite renderer:
_entity = [[BBREntity node] retain]; BBRImageRenderComponent *renderComponent = [BBRImageRenderComponent node]; [renderComponent loadImageFromFile:@"test_image.png"]; [_entity addComponent:renderComponent name:@"Render"]; _entity.position = ccp(100,100); [self addChild:_entity];
And then here is how you add a touch component to it to make it do something when you click on it:
_entity = [[BBREntity node] retain]; _entity.name = @"Entity 1"; BBRImageRenderComponent *renderComponent = [BBRImageRenderComponent node]; [renderComponent loadImageFromFile:@"test_image.png"]; [_entity addComponent:renderComponent name:@"Render"]; BBRTouchEntityComponent *touch = [BBRTouchEntityComponent node]; [_entity addComponent:touch name:@"touch"]; _entity.position = ccp(100,100); [self addChild:_entity];
Simple huh. Each entity is added to the layer and that added to the scene. You can see the similarities to the PushButton Game Framework ;P
I have also implemented a way to add/remove/dispatch events inside of components plus a hash lookup system to manage entities.
Next on my list is to implement some audio components then I can start using it to build my game. Unfortunately no physics components yet because the game I am working on doesn’t need it.
I’m very interested in your idea here… Would you mind elaborating a bit more on how you set up your entity? I apologize, but I’m new to OOP, and Objective-C, so I’m struggling to understand what you mean. Is your entity a subclass of CCNode?
Thanks!
–Joe
Yes, my entity is a subclass of CCNode both EntityComponent and Entity are subclasses of CCNode. Although in hindsight, I think I will make EntityComponent derive from NSObject instead because I don’t need it to be inheritted from CCNode
The entity itself get’s attached to the appropriate layers(CCLayer). Right now I use my own method on the entity to add/delete components
Thanks for the reply! I was thinking about doing it this way as well. I’m glad to know that I was thinking along the same lines as an experienced developer!