cocos2d是通用游戏引擎,为了保持兼容性与易用性,将动画封装为一个Action。简单的过程就是:使用CCTexture2D生成对应的CCSpriteFrame,然后将CCSpriteFrame添加到CCAnimation中生成动画数据,再用CCAnimation生成CCAnimate(最终的动画动作),最后用CCSprite执行这组动作。相关类的关系如图:
相关代码如下:
CCSize s = CCDirector::sharedDirector()->getWinSize(); CCTexture2D* texture2D = CCTextureCache::sharedTextureCache()->addImage("animation.png"); CCSpriteFrame* frame0 = CCSpriteFrame::frameWithTexture(texture2D, CCRectMake(32 * 0, 0, 32, 48)); CCSpriteFrame* frame1 = CCSpriteFrame::frameWithTexture(texture2D, CCRectMake(32 * 1, 0, 32, 48)); CCSpriteFrame* frame2 = CCSpriteFrame::frameWithTexture(texture2D, CCRectMake(32 * 2, 0, 32, 48)); CCSpriteFrame* frame3 = CCSpriteFrame::frameWithTexture(texture2D, CCRectMake(32 * 4, 0, 32, 48)); CCArray* animFrames = CCArray::createWithCapacity(4); animFrames->addObject(frame0); animFrames->addObject(frame1); animFrames->addObject(frame2); animFrames->addObject(frame3); CCAnimation* animation = CCAnimation::animationWithSpriteFrames(animFrames, 0.2f); animFrames->release(); CCSprite* sprite = CCSprite::spriteWithSpriteFrame(frame0); sprite->setPosition(ccp(s.width / 2, s.height / 2)); this->addChild(sprite); CCAnimate* animate = CCAnimate::actionWithAnimation(animation); sprite->runAction(CCRepeatForever::actionWithAction(animate));