[cocos2d-x篇]新增一個動畫的Sprite

cocos2dx使用版本︰v2.0.4
cocosBuilder使用版本︰v2.0 alpha 1

CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();

                    cache->addSpriteFramesWithFile("images2.plist");

            CCArray *animFrame = new CCArray(4);

            CCSpriteFrame *frame = cache->spriteFrameByName("girl1.png"); // 加進第1幀

                animFrame->addObject(frame);

                frame = cache->spriteFrameByName("girl2.png"); // 加進第2幀

                animFrame->addObject(frame);

                frame = cache->spriteFrameByName("girl3.png"); // 加進第3幀

                animFrame->addObject(frame);

                frame = cache->spriteFrameByName("girl4.png"); // 加進第4幀

                animFrame->addObject(frame);

                CCAnimation* animation = new CCAnimation();

                animation->initWithSpriteFrames(animFrame,0.1f);

                animation->autorelease();

                ////创建动画 

           CCAnimate *animate = CCAnimate::actionWithAnimation(animation); 

           CCSprite* pSprite1 = CCSprite::createWithSpriteFrameName("girl1.png");

          
           pSprite1->setPosition(ccp(100,300));

           pSprite1->runAction(CCRepeatForever::actionWithAction(animate));

          this->addChild(pSprite1,0);
另一種由影像載入的方式
                CCTexture2D *pTexture=CCTextureCache::sharedTextureCache()->addImage("hero.png");  
    CCSpriteFrame *frame0=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(0,0,32,32));  
    CCSpriteFrame *frame1=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(32,0,32,32));  
    CCSpriteFrame *frame2=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(64,0,32,32));  
    CCSpriteFrame *frame3=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(96,0,32,32));  
    CCArray  *animFrames=CCArray::create();  
    CC_BREAK_IF(!animFrames);  
    animFrames->addObject(frame0);  
    animFrames->addObject(frame1);  
    animFrames->addObject(frame2);  
    animFrames->addObject(frame3);  
      
    CCAnimation *animation=CCAnimation::createWithSpriteFrames(animFrames,0.2f);  
      
    CC_BREAK_IF(!animation);  
      
    CCSprite *heroSprite0=CCSprite::createWithSpriteFrame(frame0);  
    CC_BREAK_IF(!heroSprite0);  
    heroSprite0->setPosition(ccp(100,100));  
    addChild(heroSprite0,1);  
    CCAnimate *animate=CCAnimate::create(animation);  
    heroSprite0->runAction(CCRepeatForever::create(animate));//一直执行下去

沒有留言 :

張貼留言