CCSpriteBatchNode和CCSpriteFrameCache的区别及用法

来源:互联网 发布:域名管理系统源码 编辑:程序博客网 时间:2024/05/05 20:50

在我们面试使用Cocos2dx 开发游戏的公司时候,有可能会问到CCSpriteBatchNode和CCSpriteFrameCache的区别有什么?

   总的讲CCSpriteBatchNode是读取一张图(或者是一张大图)根据Rect读取不同纹理,返回小图给Sprite使用。CCSpriteFrameCache读取拼图和plist,可以根据图片名字获取小的纹理图。


1:CCSpriteBatchNode

      在屏幕上面绘制一张图片时,图形处理器会先准备渲染, 然后渲染图形,完成渲染后进行清理,这就是对一张图片开始渲染、结束渲染的系统开销。如果使用一张纹理贴图渲染一组精灵,图形处理器硬件只需要执行一次准备、渲染、完成渲染进行清理。

      我们在使用一张图片多次出现在屏幕中的时候就可以使用CCSpriteBatchNode,会减少图形处理器硬件渲染图片对系统的开销。

   

我们测试使用普通的CCSprite添加1000张图片   

for(int i = 0;i < 1000;++i){int x = arc4random()%960;int y = arc4random()%640;CCSprite* testIcon = CCSprite::create("Icon.png");testIcon->setPosition( ccp(x, y) );this->addChild(testIcon);}

我们会在左下角看到FPS 等一些信息。  此时显示的是渲染的批次是 1000.


我们使用CCSpriteBatchNode同样添加1000张图片    

CCSpriteBatchNode* batchNode = CCSpriteBatchNode::create("Icon.png", 1000);batchNode->setPosition(CCPointZero);this->addChild(batchNode);for(int i = 0;i < 1000;++i){ int x = arc4random()%960;int y = arc4random()%640;CCSprite* testIcon = CCSprite::createWithTexture(batchNode->getTexture());testIcon->setPosition( ccp(x, y) );batchNode->addChild(testIcon);}

然而此时显示:渲染批次是 1.

// 利用贴图创建,默认子节点的数量是29(数量不够时,系统会自己增加)

CCSpriteBatchNode::create(const char* fileImage);


// 创建贴图并指定子节点的数量

CCSpriteBatchNode::create(const char* fileImage, unsigned int capacity);


2:CCSpriteFrameCache

      将精灵添加到精灵帧缓存中

CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();   cache->addSpriteFramesWithFile("animations/grossini.plist", "animations/grossini.png");   m_pSprite1 = CCSprite::spriteWithSpriteFrameName("grossini_dance_01.png");   m_pSprite1->setPosition( ccp( s.width/2-80, s.height/2) );  this->addChild(m_pSprite);


结合使用看到更清楚明了

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("animations/ghosts.plist", "animations/ghosts.png");        CCSpriteBatchNode *aParent = CCSpriteBatchNode::batchNodeWithFile("animations/ghosts.png");     addChild(aParent, 0, kTagSprite1);        CCSprite *pFather = CCSprite::spriteWithSpriteFrameName("father.gif");     pFather->setPosition(ccp( s.width/2, s.height/2));     aParent->addChild(pFather, 0, kTagSprite2); 


大致就是这样,在后面如有更好的解释修改。



-------------------------------------我的一步步的爬坑---------------------



0 0
原创粉丝点击