1

My task is to draw one sprite 100 times in frame. For example I need to draw a row made of one sprite "sprite.png". I do it like this:

CCSprite *spriteArr[ 100 ];

for ( unsigned int i = 0; i < 100; i++ ) {

    spriteArr[ i ] = new cocos2d::CCSprite();
    spriteArr[ i ]->initWithFile( "sprite.png" );
    spriteArr[ i ]->setPosition( cocos2d::CCPoint( i * 10, 100 ) );

    this->addChild( spriteArr[ i ] );

}

And that's the problem. I allocate memory 100 times just only for one sprite but I don't know how to do it differently. How can I optimize it? Is there a way in Cocos2d for drawing a sprite using coordinates (x and y) but not to allocate memory for each same sprite?

JavaRunner
  • 2,455
  • 5
  • 38
  • 52

2 Answers2

6

Cause all the 100 sprites used the same texture,so the best way is to use CCSpriteBatchNode. It will draw them in 1 single OpenGL call.

CCSpriteBatchNode* batchNode = CCSpriteBatchNode::create("sprite.png", 100);
batchNode->setPosition(CCPointZero);
this->addChild(batchNode);

for(int i = 0;i < 100;++i)
{
   CCSprite* sprTest = CCSprite::createWithTexture(batchNode->getTexture());
   sprTest->setPosition(ccp(i*10,100));
   batchNode->addChild(sprTest);
}
PeakCoder
  • 852
  • 8
  • 20
  • @LearnCocos2D OpenGL ES draw call also consumes memory..A CCSpriteBatchNode can reference one and only one texture atlas.This does optimize memory. – PeakCoder Apr 05 '13 at 08:31
  • I don't think this makes any real difference, especially when you compare it with the amount of memory of even a small texture. – CodeSmile Apr 05 '13 at 09:45
  • @LearnCocos2D you better run instrument to check the difference – PeakCoder Apr 05 '13 at 09:58
  • 5
    In case of not using batching there will be lags not because of memory, but because of large amount of draw calls. I think you both know it =) So to reduce memory - yeah, JavaRunner can use pvr.ccz format. To remove lags because of drawing hundred of sprites - he should use batch node =) – Morion Apr 05 '13 at 13:21
4

You're good. All 100 sprites will reference the same texture object, so it's just a single texture in memory. Each sprite instance adds less than 500 bytes of memory on top of that.

Your best option to conserve memory is to use the .pvr.ccz format for images.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217