• cocos2dx中快速完成一段可播放动画


    版本:cocos2dx 2.2.6

    IDE: VS2012

    语言:C++98

    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    cache->addSpriteFramesWithFile("walk.plist");
    CCSprite* pSprite = CCSprite::createWithSpriteFrameName("zzlx1.JPG");
    pSprite->setPosition(ccp(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2));

    首先将图片资源加载到内存中去,用精灵帧缓存的方式来创建精灵。

    精灵创建的方式有多种,但是精灵帧缓存创建精灵的方式最为常用,因为占用内存和效率。

    相关知识:http://www.cnblogs.com/andyque/articles/1988097.html

    pSprite精灵是动画帧的第一张图,接下来我们需要一个数组存储剩余的动画帧

    CCArray* pArray = CCArray::create();
    char name[20];
    for (int i = 2;i <= 8; i++)
    {
        sprintf(name, "zzlx%d.JPG", i);
        pArray->addObject(cache->spriteFrameByName(name));
    }

    一共8张图,名称为zzlx1到zzlx8,这里有2点要注意的:

    1.名称最好符合某种规律,否则需要一个字符串数组来存一个动画的动画帧名称。

    2.这里JPG是大小写敏感的,我的图片名称结尾是大写JPG。如果代码中是小写则会出错。

    数组创建好后,我们来创建Animation和Animate。

    CCAnimation* pAnimation = CCAnimation::createWithSpriteFrames(pArray,0.1f);
    CCAnimate* pAnimate = CCAnimate::create(pAnimation);
    pSprite->runAction(CCRepeatForever::create(pAnimate));
    this->addChild(pSprite);

    Animation是动画,存储了所有的精灵帧和播放间隔。而Animate是动作,是Action。Action是作用于CCSprite的。

    这里CCRepeatForever是循环播放,最后将pSprite加入层中。

    全部代码:

    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    cache->addSpriteFramesWithFile("walk.plist");
    CCSprite* pSprite = CCSprite::createWithSpriteFrameName("zzlx1.JPG");
    pSprite->setPosition(ccp(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2));
        
    //精灵帧数组
    CCArray* pArray = CCArray::create();
    char name[20];
    for (int i = 2;i <= 8; i++)
    {
        sprintf(name, "zzlx%d.JPG", i);
        pArray->addObject(cache->spriteFrameByName(name));
    }
    
    CCAnimation* pAnimation = CCAnimation::createWithSpriteFrames(pArray,0.1f);
    CCAnimate* pAnimate = CCAnimate::create(pAnimation);
    pSprite->runAction(CCRepeatForever::create(pAnimate));
    this->addChild(pSprite);

    cocos2dx中的三种缓存

    http://blog.csdn.net/star530/article/details/23612487

    这里AnimationCache,动画缓存,参考资料中并没有写完整,使用动画缓存如果用一般的plist文件是不行的,需要特殊生成plist文件,

    这样的plist文件会一个key对应一组图片,这样使用key就能载入一组完整的动画帧,播放动画。

    最终效果

  • 相关阅读:
    ps命令
    关于typedef的用法总结
    C#中正则表达式的使用
    调试与编译
    大端和小端
    64位程序内存之我看
    C/C++内存泄漏及检测
    内核中的 likely() 与 unlikely()
    do/while(0) c4127
    django+xadmin在线教育平台(六)
  • 原文地址:https://www.cnblogs.com/beyond-time-space/p/4566795.html
Copyright © 2020-2023  润新知