Search code examples
c++cocos2d-xcocos2d-x-3.0

Cocos2d-x 3.2 Error - Change Arrays to Vectors?


I am getting an error with the following code because I am using arrays instead of vectors. What would be the best way to write this code using vectors?

CCAnimate* createAnimate(int frameCount, float duration, const char* imageName)
{
   CCArray * spritesArray = CCArray::create();

   for (int i = 0; i < frameCount; i++) {

      CCString *spritePath = CCString::createWithFormat("%s%i.png",imageName,i);
      CCSprite *sprite = CCSprite::create(spritePath->getCString());
      spritesArray->addObject(sprite);

   }

   CCArray *animationFrames = CCArray::create();

   for (int i = 0; i < spritesArray->count(); i++) {

      CCSprite *sprite = (CCSprite*)spritesArray->objectAtIndex(i);
      CCSpriteFrame *frame = sprite->displayFrame();
      animationFrames->addObject(frame);

   }

   CCAnimation* animation =  CCAnimation::createWithSpriteFrames(animationFrames,duration);
   CCAnimate* animate= CCAnimate::create(animation);

   return animate;    
}

Solution

  • Vector<SpriteFrame*> VillanspriteFrames(frameCount);
        for (int i = 1; i <= frameCount; i++) {
        char fileName[128] = { 0 };
        sprintf(fileName, "imageName%d.png", i);
    
        auto frames = spriteCache->getSpriteFrameByName(fileName);
        VillanspriteFrames.pushBack(frames);
    }
    
    auto swordRun = Animation::createWithSpriteFrames(VillanspriteFrames,
            duration);
    swordRun->setRestoreOriginalFrame(true);
    auto animate = Animate::create(swordRun);
    return animate;
    

    To use this code u have to use a .plist file using Texture packer, pack all the files in it using desired names. Add a Texture file in your Init Method like...

    SpriteFrameCache *spriteCachespriteCache = SpriteFrameCache::getInstance();
    spriteCache->addSpriteFramesWithFile("FightAnim.plist", "FightAnim.png");
    

    SpriteFrameCache is a singleton object. Hope this helps You.