Thursday, September 3, 2009

Extending cocos2d

Today was my first real day of doing something vaguely productive using cocos2d on the iPhone.

I coded an animation creation framework (aptly called Pixel Animation Studio) some months ago which can be used to compose animations using 2d pixel graphics. Basically, an animation is broken down into frames which in turn are broken down into small fragments. This technique encourages reuse of image fragments and can save a lot of space normally wasted by duplicate content in images. I guess you can see my background as a J2ME engineer shine through ...

Anyways, to support the animations created using this tool, I need a Sprite class that can be assembled by rendering multiple images instead of a single texture. To get this working, I investigated the CocosNode, TextureNode and Sprite source code to see, how rendering is performed deep within cocos2d. Turns out it's fairly easy to do:

cocos2d already handles most of the behaviour you need for a Sprite in CocosNode. It takes care of position translations and rendering all the sub-nodes added to a CocosNode. Now you just go ahead, sub-class CocosNode and add all the images you'd like to render as children of type Sprite (or AtlasSprite). cocos2d will take care of the rest!

Since the animations produced with Pixel Animation Studio are slightly more advanced than the ones provided out of the box by cocos2d (btw, I didn't realize plain 2d, frame-based animations were supported out of the box to begin with - they are just not properly highlighted as a feature on their site), I also had to implement a new IntervalAction. That's pretty straight-forward, too: just subc-class and override the + (void) update: (ccTime) time method. When instantiating, keep in mind that cocos2d takes parameters in seconds for the actions which accept a duration parameter, not in milliseconds.

No comments:

Post a Comment