Sprite中图片加载会占用内存,而多次使用同一个图片精灵时,会使用到缓存机制。 还有有多个角色,多个怪物,多个动作时,要怎么利用内存的缓存机制。


1. 纹理缓存(图片缓存) CCTexture2D.h (整个引擎只有一个)

以文件名创建精灵时,其实还是要先加载成CCTexture2D,也可以直接用CCTexture2D创建。CCTexture2D有机制实现缓存。

bool CCSprite::initWithFile(const char *pszFilename)

{

CCAssert(pszFilename != NULL, "Invalid filename for sprite");


CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(pszFilename);

if (pTexture)

{

CCRect rect = CCRectZero;

rect.size = pTexture->getContentSize();

return initWithTexture(pTexture, rect);

}


// don't release here.

// when load texture failed, it's better to get a "transparent" sprite then a crashed program

// this->release();

return false;

}

for(int i=0; i<9999; i++)

{

CCSprite* mysprite = CCSprite::create("CloseSelected.png");

mysprite->setPosition( ccp (CCRANDOM_0_1()*480,CCRANDOM_0_1()*320) );

this->addChild(mysprite,1);

}

for(int i=0; i<99; i++)

{

CCSprite* mysprite = CCSprite::create("CloseSelected.png");

mysprite->setPosition(ccp(CCRANDOM_0_1()*480,CCRANDOM_0_1()*320));

this->addChild(mysprite,1);

}

精灵帧缓存(动画帧)

CCSpriteBatchNode* batchSprite = CCSpriteBatchNode::create("CloseSelected.png");

batchSprite->setPosition(CCPointZero);

this->addChild(batchSprite,1);

for (int i = 0; i<99 ; i++)

{

CCSprite* mysprite2 = CCSprite::createWithTexture(batchSprite->getTexture());

mysprite2->setPosition(ccp(CCRANDOM_0_1()*360,CCRANDOM_0_1()*240));

this->addChild(mysprite2,1);

}


CCSpriteBatchNode,批精灵创建,可以认为是一个精灵容器。


3.动画缓存

采用地图编辑器,将小图片编辑到一张大图片上,然后生成一张大图片和对应的plist文件。

在plist文件中存放的每一帧都是一张小图片,在plist中旋转的图片在作为帧被使用时会自动还原。

plist文件中每一帧的文件仍是源文件的名字,加载时使用小图片的名字即可,而且源文件被删除也不影响plist文件的使用。







缓存机制

CCSpriteCCTexture2D
CCTextureCache




CCSpriteBatchNodeCCTextureAtlas
CCTextureCache






CCAnimation

CCAnimationFrame

CCSpriteFrameCCSpriteFrameCache


CCAnimationCache


CCTexturePcaker