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;
}