原地址:http://www.cnblogs.com/BeemanComing/archive/2011/10/29/2228466.html
一般游戏图片资源会打包成一张大图,这样节省空间,又提升速度。打包工具有Zwoptex和texturepacker等等。
CCSpriteBatchNode的初始化只要一张图片,也就是那张大图。然后把所有用到那张大图里面的小图的sprite都加到 CCSpriteBatchNode的child,绘制效率就会提高。
1) 缓冲sprite帧和纹理
// 从纹理贴图集中预加载精灵帧,这个方法做了以下几件事:
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"table.plist"];
CCSpriteBatchNode *spriteNode = [CCSpriteBatchNode batchNodeWithFile:@"table .png"];[self addChild:spriteNode];
2) 创建一个精灵批处理结点
// 为所有 静态刚体 设置的批处理精灵节点
CCSpriteBatchNode* batch = [CCSpriteBatchNode batchNodeWithFile:@"table.png"];
[self addChild:batch];
CCSprite* tableTop = [CCSprite spriteWithSpriteFrameName:@"tabletop.png"];
tableTop.position = [Helper screenCenter];
[batch addChild:tableTop];
-(CCSpriteBatchNode*) getSpriteBatch
{
return (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode];
}
CCSpriteBatchNode* batch = [[PinballTable sharedTable] getSpriteBatch];
sprite = [CCSprite spriteWithSpriteFrameName:spriteFrameName];
[batch addChild:sprite];
//Batch是一个CCSpriteBatchNode,下面Batch-》Sprite-》ChildrenSprite,
//它们的Tag分别为:TagofBatch,TagofSprite,TagofChildrenSprite 得到ChildSprite的方法如下,
根据各自的Tag得到相应的数据。
id Batch = [self getChildByTag:TagofBatch];
id Sprite = [Batch getChildByTag:TagofSprite];
CCSprite *ChildrenSprite = (CCSprite*) [Sprite getChildByTag:TagofChildrenSprite];
關於CCSpriteBatchNode,一个CCSpriteBatchNode是一种效率比较高的渲染精灵的方式。比如,你把CCSprite加到CCLayer中,那么sprite的draw函数在 每一帧调用时都会执行7个opengl 调用来完成sprite的渲染。一个精灵的时候当然没问题,但是,当你在屏幕上有200个精灵的时候,那么就会有200×7次opengl调用。。。而 CCSpriteBatchNode可以“批处理”它的孩子精灵的draw调用。这意味着,当把200个精灵加到 Spritesheet中去的时候,只要使用7个opengl调用就可以完成200个孩子的渲染了。
cocos2d裏面的描述
CCSpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call (often known as "batch draw").
A CCSpriteBatchNode can reference one and only one texture (one image file, one texture atlas). Only the CCSprites that are contained in that texture can be added to the CCSpriteBatchNode. All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
Limitations: