温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

十:Cocos2d-x缓存机制

发布时间:2020-06-21 20:57:40 来源:网络 阅读:760 作者:lambdaX 栏目:游戏开发

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


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

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

  1. bool CCSprite::initWithFile(const char *pszFilename)

  2. {

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


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

  5.     if (pTexture)

  6.     {

  7.         CCRect rect = CCRectZero;

  8.         rect.size = pTexture->getContentSize();

  9.         return initWithTexture(pTexture, rect);

  10.     }


  11.     // don't release here.

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

  13.     // this->release(); 

  14.     return false;

  15. }

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

  17. {

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

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

  20. this->addChild(mysprite,1);

  21. }

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

  23. {

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

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

  26. this->addChild(mysprite,1);

  27. }

  28. 精灵帧缓存(动画帧)

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

  30. batchSprite->setPosition(CCPointZero);

  31. this->addChild(batchSprite,1);

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

  33. {

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

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

  36. this->addChild(mysprite2,1);

  37. }


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


3.动画缓存

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

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

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







缓存机制

CCSpriteCCTexture2D
CCTextureCache




CCSpriteBatchNodeCCTextureAtlas
CCTextureCache






CCAnimation

CCAnimationFrame

CCSpriteFrameCCSpriteFrameCache



CCAnimationCache


CCTexturePcaker



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI