http://download.csdn.net/detail/wu_123_456/7615263
1.在init()函數中添加如下代碼:
CCSprite* sprite2 = CCSprite::create("animation.png",CCRectMake(1,1,200,285));
sprite2->setPosition(ccp(200,150));
this->addChild(sprite2,4);
sprite2->runAction(createAnimation());
CCRectMake功能是在該圖片資源中截取某一部分。
2.createAnimation()函數的創建
CCAction* NodeHelloWorld::createAnimation()
{
CCSpriteBatchNode *bathnode = CCSpriteBatchNode::create("animation.png");
int iFrameNum = 4;
CCSpriteFrame* frame = NULL;
CCArray* frameArray = CCArray::create();
for (int i = 0; i < iFrameNum ;++i)
{
int x = i*200+1;
int y = 1;
frame = CCSpriteFrame::createWithTexture(bathnode->getTexture(),CCRectMake(x,y,200,285));
frameArray->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(frameArray);
animation->setLoops(-1);
animation->setDelayPerUnit(0.5f);
CCAction* action = CCAnimate::create(animation);
return action;
}
創建動畫,過程中使用CCSpriteFrame幀控制,再由幀創建出CCAnimation(名詞),要想動起來,還得創建動作(也就是動詞)CCAnimate,對於內存中的優化,在上述代碼中使用的是CCSpritebatchNode,也可使用精靈幀緩存類CCSpriteFrameCache,如上一篇中所描述,要有plist文件。
參考代碼:
CCAction* TollgateScene::createAnimation()
{
CCSpriteFrameCache *boysCache = CCSpriteFrameCache::sharedSpriteFrameCache();
boysCache->addSpriteFramesWithFile("boys.plist","boys.png");
CCSpriteFrame *frame = NULL;
CCArray* framearray = CCArray::create();
for (int i = 1; i <= MAX_BOYS_COUNTS;++i)
{
CCString *str = CCString::createWithFormat("run%d.png",i);
frame = boysCache->spriteFrameByName(str->getCString());
framearray->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(framearray);
animation->setLoops(-1);
animation->setDelayPerUnit(0.03f);
CCAction* action = CCAnimate::create(animation);
return action;
}