I have built a little ipad game and spritesheets and batchnodes are all over the place. However I have no idea how they really work, when to add a sprite sheet, when to add sprites to the spritebatchnode etc. etc. .
This is what I do in the initial screen (main menu):
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"sprites.png"];
screenSize = [CCDirector sharedDirector].winSize;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"sprites.plist"];
[self addChild:spriteSheet];
In other classes – I always need to use the same batch node -> “sprites.png” – I call
CCSprite *someSprite = [CCSprite spriteWithSpriteFrameName:someSpriteFrameName.png];
and add it to self.
[self addChild:someSprite]; // I do not understand why I would add my sprite to the batch node instead of self
So the situation is the following:
-
I have 1 file called “sprites.png” where all my sprites are on.
- Do I make a new batch node whenever I change the scene ? The spriteframecache should stay the same right ?
- What would I have to do with the spriteframecache if i had two sprite sheet files ?
- When do I add children to the batch node, and why ?
I really don’t seem to grasp the concept entirely. I know approximately why I use it. But I would really appreciate it if somebody could explain everything to me again in layman terms, so I am 100% sure about what I do. Please try to explain it as basic as it gets.
- Thank you very much –
Martin
CCSpriteBatchNode is CCNode successor so you have to create separate instance for every scene. You can use several batch nodes on the scene if you have more than one texture file.
CCSpriteFrameCacheis a singleton so it stays the same during application lifetime.Add both to
CCSpriteFrameCache.CCSpriteFrameCachesingleton hasloadedFilenames_field (instance ofNSMutableSet) which caches all sprite frames for all scenes.You have to use batch node when you expect large amount of sprites with similar textures. For example you want to generate 100 coins every 2 seconds. If you use usual
CCNodeand create sprites on it, your application will allocate these 100CCSpriteobjects every 2 seconds.CCSpriteBatchNodeis targeted for performance and better memory usage. It works likeUITableViewwith reusable cells.When you scroll table view with reusable cells, it does not create new cells. When new cell has to be presented on screen table view simply finds cell with same reuse identifier offscreen and replaces it’s content with new content.
CCSpriteBatchNodeworks in the same way. When you try to add new sprite to it, the node tries to find unused sprite offscreen and replaces it’s content.Remember that sprites which you add to
CCSpriteBatchNodehave to use the textures from texture file which was used to create this batch node.Following example is based on code from your question:
Here is a good article about CCSpriteBatchNode performance: http://www.learn-cocos2d.com/2011/09/cocos2d-spritebatch-performance-test/