cocos2d-x 3.x(实现帧动画的几种方法)

cocos2d-x 3.x(实现帧动画的几种方法)

方法一(动画帧):
//创建一个跑酷的精灵auto sprite = Sprite::create("1.png");

 //设置精灵的坐标

 sprite->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));

//添加到当前层this->addChild(sprite);

//创建序列帧动画auto animation = Animation::create();

//设置动画名字数组的长度char nameSize[20] = {0};

 //动画的循环 12张图片for (int i =1; i<13; i++)

 {

       //循环遍历sprintf(nameSize, "%d.png",i);

         //添加到序列帧动画

     animation->addSpriteFrameWithFile(nameSize);

 }

//设置动画帧的时间间隔

animation->setDelayPerUnit(0.02f);

//设置播放循环 一直播放 为-1

animation->setLoops(-1);

//设置动画结束后恢复到第一帧

animation->setRestoreOriginalFrame(true);

 //创建动画动作auto animate = Animate::create(animation);

 //播放动画

sprite->runAction(animate);
方法二(vector):
//帧动画缓存auto frameCache = SpriteFrameCache::getInstance();

 frameCache02->addSpriteFramesWithFile("1.plist");

 //创建一个显示动画的精灵auto sprite = Sprite::createWithSpriteFrameName("1.png");

//设置动画的坐标

sprite->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));

//添加到当前层this->addChild(sprite);

//
创建一个容器
 Vector vec;

 //设置动画名字数组的长度char name[20] = {0};

 for (int i = 1; i<13; i++) {

//遍历sprintf(name, "%d.png",i);

vec.pushBack(frameCache->getSpriteFrameByName(name));

 }

 //auto animation = Animation::createWithSpriteFrames(vec,0.05f);//也是可以这么写的。那setDelayPerUnit 这个需要注释掉auto animation = Animation::createWithSpriteFrames(vec);

//设置动画帧的时间间隔

animation->setDelayPerUnit(0.05f);

 //设置播放循环 一直播放 为-1

 animation->setLoops(-1);

//设置动画结束后恢复到第一帧

animation->setRestoreOriginalFrame(true);

 //创建动画动作auto animate = Animate::create(animation);

 //播放动画动作

sprite->runAction(animate);
方法三(纹理):
//通过一张集合的图片来创建
    //创建2D纹理
    auto texture = Director::getInstance()->getTextureCache()->addImage("dragon_animation.png");
    //建立图片帧
    auto frame0 = SpriteFrame::createWithTexture(texture, Rect(132*0, 132*0, 132, 132));
    auto frame1 = SpriteFrame::createWithTexture(texture, Rect(132*1, 132*0, 132, 132));
    auto frame2 = SpriteFrame::createWithTexture(texture, Rect(132*2, 132*0, 132, 132));
    auto frame3 = SpriteFrame::createWithTexture(texture, Rect(132*3, 132*0, 132, 132));
    auto frame4 = SpriteFrame::createWithTexture(texture, Rect(132*0, 132*1, 132, 132));
    auto frame5 = SpriteFrame::createWithTexture(texture, Rect(132*1, 132*1, 132, 132));

    auto sprite2 = Sprite::createWithSpriteFrame(frame0);
    sprite2->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2));
    this->addChild(sprite2);

    //保存图片帧
    //Vector array;
    Vector<cocos2d::SpriteFrame *> array;
    array.pushBack(frame0);
    array.pushBack(frame1);
    array.pushBack(frame2);
    array.pushBack(frame3);
    array.pushBack(frame4);
    array.pushBack(frame5);

    auto animation2 = Animation::createWithSpriteFrames(array, 0.2f);  
     //此处createWithSpriteFrames()函数确实每帧间隔时间参数,需自行加上去!!!
    sprite2->runAction(RepeatForever::create(Animate::create(animation2)));

你可能感兴趣的:(cocos)