cocos2dx學習筆記之SpriteBatchNode應用

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
 */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章