天天看点

cocos2dxz之CCAnimationCache

通常情况下,对于一个精灵动画,每次创建时都需要加载精灵帧,按顺序添加到数组,再创建对应动作类,这是一个非常烦琐的计算过程。对于使用频率高的动画,比如鱼的游动,将其加入缓存可以有效降低每次创建的巨大消耗。由于这个类的目的和缓存内容都非常简单直接,所以其接口也是最简单明了的,如下所示:

/** Retruns ths shared instance of the Animation cache */
    static CCAnimationCache* sharedAnimationCache(void);
           
/** Adds a CCAnimation with a name.
    */
    void addAnimation(CCAnimation *animation, const char * name);
           
/** Returns a CCAnimation that was previously added.
    If the name is not found it will return nil.
    You should retain the returned copy if you are going to use it.
    */
    CCAnimation* animationByName(const char* name);
           
/** Deletes a CCAnimation from the cache.
    */
    void removeAnimationByName(const char* name);
           

唯一不一样的是,这次动画缓存需要我们手动维护全部动画信息。也因为加载帧动画完全是代码操作的,目前还没有配置文件指导,所以不能像另外两个缓存那样透明化。实际上,如果考虑到两个场景间使用的动画基本不会重复,可以直接清理整个动画缓存。

所以,在场景切换时我们应该加入如下的清理缓存操作:

void releaseCaches()
    {
        CCAnimationCache::purgeSharedAnimationCache();
        CCSpriteFrameCache::sharedSpriteFrameCache()->removeUnusedSpriteFrames();
        CCTextureCache::sharedTextureCache()->removeUnusedTextures();
    }
           

值得注意的是清理的顺序,应该先清理动画缓存,然后清理精灵帧,最后是纹理。按照引用层级由高到低,以保证释放引用有效。

CCAnimationCache *animationcache = CCAnimationCache::sharedAnimationCache();
	animationcache->addAnimationsWithFile("animations/animations-2.plist");
	CCAnimation *animation = animationcache->animationByName("dance_1");//刚开始不知道这个参数是哪里来的,其实是plist里面的,你用记事本打开就可以看得到,它是一个动画标识
	animation->setRestoreOriginalFrame(true);
           
下一篇: CCSprite解析