4

I heard using CCBatchNode is way better for performances in Cocos2d. I have troubles understanding how it works. I have several subclasses of CCSprite that represent the objects in my game. So far I initialise them with the spriteWithFile: method.

I have now a spritesheet containing all my sprites (along with its plist file). How should I use it so I can beneficiate of the "single openGL draw call" ?

If I initialise my sprites by getting back a frame within the CCBatchNode will it works ?

Anyway, I have a bad time understanding CCBatchNode, some help will be great !

Regards

rmonjo
  • 2,675
  • 5
  • 30
  • 37

1 Answers1

3

Here's a quick example using CCSpriteFrameCache and CCSpriteBatchNode.

First setup the shared frame cache (think of this as the mapping between the names of your individual images and their rectangular frames within the combined batch node image):

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"spritesheet.plist" textureFile:@"spritesheet.png"];

Now create your batch node with the combined image name (this batchNode does the single draw for multiple sprites):

CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:@"spritesheet.png" capacity:20];

Now create the sprite node passing in the name of the individual image. Add it to the batch node. (Again the batchnode will be doing the draw calls so this is where the performance benefit is):

CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"name_of_your_sprite_in_plist"];
[batchNode addChild:sprite];

You can treat the sprite just like the sprite you previously created directly from a single image (but with the performance benefits of using a batch node).

Edwin Iskandar
  • 4,119
  • 1
  • 23
  • 24
  • Great answer. I suggest the OP to search for a tutorial, it will even contain details about how to manage the `batchNode` instance. – Mazyod Nov 20 '12 at 18:37
  • Thx. Also, I use `spriteWithTexture: rect:` to initialise rectangular sprites with dynamic size (then use `ccTexParams tp = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};` to make the texture fit. Now that my texture is in the spritesheet how do I do to get it back ? Thx very much for your first answer ! – rmonjo Nov 20 '12 at 19:11
  • what do you mean by get it back? You can access the texture from sprite with the texture property (also available on the sprite sheet) e.g. sprite.texture – Edwin Iskandar Nov 20 '12 at 19:25
  • the texture I want to use is embedded in the spritesheet and I need it in a CCTexture2d var to initialise my sprite since I have to define the rect of my sprite. – rmonjo Nov 20 '12 at 21:47
  • the CCTexture2D instance is available as a property of the CCSpriteBatchNode: spritesBatchNode_.texture – Edwin Iskandar Nov 21 '12 at 00:01
  • OK but the texture I want is a part of the big png that contains everything. – rmonjo Nov 21 '12 at 10:11