通过Cocos2dx中的plist文件加载动画

Loading animations through plist files in Cocos2dx

本文关键字:加载 动画 文件 plist Cocos2dx 中的 通过      更新时间:2023-10-16

这些天我正在学习使用cocos2dx。从现在起,我可以加载和播放保存为.plist文件的精灵动画。我以这种方式加载动画:

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("oras.plist");
CCAnimation *bearWalkingAnimation = CCAnimation::create();
for (int i = 0 ; i < 8 ; ++i )
{
    std::stringstream ss;
    ss << "bear" << i + 1  << ".png";
    std::string name = ss.str();
    CCSpriteFrame* sprite =  CCSpriteFrameCache::sharedSpriteFrameCache()>spriteFrameByName(name.c_str());
    bearWalkingAnimation->addSpriteFrame(sprite);
}

我相信我知道图像的名称,但现在我正在尝试组织一点我的代码。

我想知道在加载时,是否知道哪个plist文件包含精灵帧。我能做到吗?怎样

换句话说,我想写一个通用类,它只知道plist文件名就可以加载动画。类似于:

void MyLoaderClass::LoadAnimation(std::string plist_file_name){ ....}

我已经解决了从加载的plist文件构建CCDictionary的问题:

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(fileName.c_str());
mAnimation = CCAnimation::create();
CCFileUtils *fileUtils = CCFileUtils::sharedFileUtils();
const char *fullPath = fileUtils->fullPathFromRelativePath(fileName.c_str());

CCDictionary *dictionary = CCDictionary::createWithContentsOfFileThreadSafe(fullPath);
CCDictionary *framesDict = static_cast<CCDictionary*> (dictionary->objectForKey("frames"));
CCArray *keys = framesDict->allKeys();
for (int i = 0 ; i < keys->count(); ++i)
{
    CCString *spriteFileName = static_cast<CCString *> (keys->objectAtIndex(i));
    CCSpriteFrame* sprite =  CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(spriteFileName->getCString());
    mAnimation->addSpriteFrame(sprite);
}

//"horse.png"通过哪个批次节点装箱

CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("horse.png");
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("horse.plist");
// "hero" is CCSprite and "horse_1.png" is a sprite in "horse.png" batch node
hero = CCSprite::createWithSpriteFrameName("horse_1.png");
addChild(spritebatch);
spritebatch->addChild(hero);
CCLog("In the anim2");
CCArray* animFrames = CCArray::createWithCapacity(16);
char str[100] = {0};
for(int i = 1; i < 16; i++)
{
    // in my batch node all the sprite name as 'horse_1.png', 'horse_2.png'.....
    sprintf(str, "horse_%i.png", i);
    CCSpriteFrame* frame = cache->spriteFrameByName( str );
    animFrames->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, .1f);
animation->setRestoreOriginalFrame(true);
hero->runAction( CCRepeatForever::create( CCAnimate::create(animation) ) );