SpriteBatchNode类应用情况:当需要绘制多个纹理,层级相同的精灵时
SpriteBatchNode类应用好处:提高渲染效率,减少帧绘制时间,相同的精灵越多,效果越明显
假设有个绘制1000个相同精灵的需求,首先当不使用SpriteBatchNode绘制这1000个精灵时的代码和运行效果如下:
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
for (int i = 0; i<1000; ++i)
{
Sprite* sprite = Sprite::create("tree64.png");
sprite->setPosition(ccp(CCRANDOM_0_1() * visibleSize.width, CCRANDOM_0_1() * visibleSize.height));
this->addChild(sprite);
}
return true;
}
这里解释一下这3行参数,第一行表示绘制的顶点个数,第二行表示渲染批次,第三行表示帧率和每帧绘制消耗的秒数。可以看到即使在不用SpriteBatchNode的情况下,3.0后的引擎依然会在一次渲染中把相同精灵绘制出来,那么还是否需要用SpriteBatchNode呢?接下来看使用SpriteBatchNode的情况:
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
SpriteBatchNode* batchNode = SpriteBatchNode::create("tree64.png");
this->addChild(batchNode);
for (int i = 0; i<1000; ++i)
{
Sprite* sprite = Sprite::create("tree64.png");
sprite->setPosition(ccp(CCRANDOM_0_1() * visibleSize.width, CCRANDOM_0_1() * visibleSize.height));
batchNode->addChild(sprite);
}
return true;
}
可以看到当使用SpriteBatchNode时,每帧的绘制时间会有所降低,相同精灵越多效果越明显
最后附上在CCSprite.h和CCSpriteBatchNode.h中,关于SpriteBatchNode的介绍:
* To gain an additional 5% ~ 10% more in the rendering, you can parent your sprites into a `SpriteBatchNode`.
* But doing so carries the following limitations:
*
* - The Alias/Antialias property belongs to `SpriteBatchNode`, so you can't individually set the aliased property.
* - The Blending function property belongs to `SpriteBatchNode`, so you can't individually set the blending function property.
* - `ParallaxNode` is not supported, but can be simulated with a "proxy" sprite.
* - Sprites can only have other Sprites (or subclasses of Sprite) as children.
/** SpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
* (often known as "batch draw").
*
* A SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
* Only the Sprites that are contained in that texture can be added to the SpriteBatchNode.
* All Sprites added to a SpriteBatchNode are drawn in one OpenGL ES draw call.
* If the Sprites are not added to a SpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
*
*
* Limitations:
* - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is Sprite or any subclass of Sprite. eg: particles, labels and layer can't be added to a SpriteBatchNode.
* - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture.
*
* @since v0.7.1
*/