Cocos2d-x:自定义动画 使用plist来实现


使用plist文件,结合cocos2dx里面的动画类Animation来实现,这种方式比较推荐



代码如下:


void BaseLayer::testTextture(){
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vector<SpriteFrame*> spriteFrameVec;
    auto spriteFrameCache = SpriteFrameCache::getInstance();
    
    // 这里使用plist文件
    spriteFrameCache->addSpriteFramesWithFile("test.plist", "test.png");
    
    char path[256] = { 0 };
    for (int i = 1; i <= 6; ++i)
    {
        sprintf(path, "%d.png", i);
        log("path = %s", path);
        SpriteFrame *pSpriteFrame = spriteFrameCache->getSpriteFrameByName(path);
        spriteFrameVec.pushBack(pSpriteFrame);
    }
    
    // 0.1那个参数必须设定,可以设定除默认值意外的任何值,如果你不设定,根本就无法播放Animate动作
    // Cocos2d-x的坑还不少啊,各位需谨慎啊
    auto animation = Animation::createWithSpriteFrames(spriteFrameVec, 0.1);
    animation->setDelayPerUnit(2.8f / 14.0f);//必须设置否则不会动态播放
    animation->setRestoreOriginalFrame(true);//是否回到第一帧
    animation->setLoops(-1);//重复次数 (-1:无限循环)
    
    auto sprite = Sprite::create();
        // 方法1:从SpriteFrameCache中根据名字获得对应的精灵帧,再设置
    sprite->setSpriteFrame(spriteFrameCache->getSpriteFrameByName("1.png"));
    
    // 方法2:从Animation中获得对应的帧,再进行设置
    AnimationCache::getInstance()->addAnimation(animation, "dogs");
    // sprite->setDisplayFrameWithAnimationName("dogs", 0);
    
    sprite->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
    addChild(sprite, 1, 1);
    
    FiniteTimeAction * animate = Animate::create(animation);
    sprite->runAction(animate);

}



官方文档:


You have to tell cocos2d-x which sprite frames should be used in an animation. The easiest way for this is to create a helper method that creates a list:

Vector HelloWorld::getAnimation(const char *format, int count)
{
    auto spritecache = SpriteFrameCache::getInstance();
    Vector animFrames;
    char str[100];
    for(int i = 1; i <= count; i++)
    {
        sprintf(str, format, i);
        animFrames.pushBack(spritecache->getSpriteFrameByName(str));
    }
    return animFrames;
}
This method retrieves the animation frames from the sprite sheet that follow a given format. You can call it in the following way:

Vector frames = getAnimation("capguy/walk/%04d.png", 8);
The format string %04d creates 4 digit numbers prefixed with 0: 0001, 0002, 0003,...

The call returns a list of 8 sprite frames: capguy/walk/0001.png,... capguy/walk/0008.png

Add the
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值