使用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