void Llama::preloadResources(){ //Cache de sprites auto spriteFrameCache = SpriteFrameCache::getInstance(); //Cache de animaciones auto animCache = AnimationCache::getInstance(); //Si no estaba el spritesheet en la caché lo cargo if(!spriteFrameCache->getSpriteFrameByName("fuego1.png")) { spriteFrameCache->addSpriteFramesWithFile(OBJETOS_PLIST); } m_anim = Animation::create(); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego1.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego2.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego3.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego4.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego5.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego6.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego7.png")); m_anim->addSpriteFrame(spriteFrameCache->getSpriteFrameByName("fuego8.png")); m_anim->setDelayPerUnit(.15f); m_anim->retain(); animCache->addAnimation(m_anim, "Llama"); }
MayBay * MayBay::Create(){ MayBay * obj = new MayBay(); auto SpFrameCache = SpriteFrameCache::getInstance(); SpFrameCache->addSpriteFramesWithFile("plane/plane.plist"); if(!obj->initWithSpriteFrame(SpFrameCache->getSpriteFrameByName("planeRed1.png"))){ CCLOG("Cant not create maybay"); } else{ Vector<SpriteFrame*> vecFrm(3); char str[50]={0}; for(int i=1; i<=3 ;i++){ sprintf(str,"planeRed%d.png",i); auto spFrm = SpFrameCache->getSpriteFrameByName(str); vecFrm.pushBack(spFrm); } auto animation = Animation::createWithSpriteFrames(vecFrm,0.1f); auto ani= Animate::create(animation); obj->runAction(RepeatForever::create(ani)); } auto physic = PhysicsBody::createBox(Size(Vec2(obj->getContentSize().width-10,obj->getContentSize().height-10)),PhysicsMaterial(1,0,1)); physic->setCollisionBitmask(0x001); physic->setCategoryBitmask(0x001); physic->setContactTestBitmask(true); physic->setTag(10); obj->setPhysicsBody(physic); obj->getPhysicsBody()->setGravityEnable(false); obj->setFly(); return obj; }
void Tutorial::Crash()// draws the animation for a crash and pasticles that fly out from there { //animation code auto spritecache = SpriteFrameCache::getInstance(); spritecache->addSpriteFramesWithFile("GameScreen/explosion.plist"); cocos2d::SpriteFrame* spriteFrame = spritecache->getSpriteFrameByName("explosion0.png"); cocos2d::Vector<cocos2d::Sprite *> m_aiSprites; cocos2d::Vector<cocos2d::SpriteFrame*> m_animFrames; for (int i = 0; i < 23; i++) { // Get a SpriteFrame using a name from the spritesheet .plist file. m_animFrames.pushBack(spritecache->getSpriteFrameByName("explosion" + std::to_string(i) + ".png")); } // Create the animation out of the frames. Animation* animation = Animation::createWithSpriteFrames(m_animFrames, 0.065); Animate* animate = Animate::create(animation); // Create a sprite using any one of the SpriteFrames // This is so we get a sprite of the correct dimensions. auto sprite = Sprite::createWithSpriteFrame(m_animFrames.at(0)); // Run and repeat the animation. sprite->setScale(3.0f); sprite->runAction(RepeatForever::create(animate)); sprite->setPosition(Vec2(player->getPosition().x, player->getPosition().y - 5)); this->addChild(sprite, 10); m_aiSprites.pushBack(sprite); //code for the particles that will be coloured orange auto size = Director::getInstance()->getWinSize(); auto m_emitter = ParticleExplosion::createWithTotalParticles(900); m_emitter->setDuration(-1); m_emitter->setGravity(Point(0, -240)); m_emitter->setAngle(0); m_emitter->setAngleVar(180); m_emitter->setRadialAccel(25); m_emitter->setRadialAccelVar(0); m_emitter->setTangentialAccel(10); m_emitter->setTangentialAccelVar(0); m_emitter->setPosVar(Point(1, 0)); m_emitter->setLife(0.25); m_emitter->setLifeVar(0.50); m_emitter->setStartSpin(0); m_emitter->setStartSpinVar(0); m_emitter->setEndSpin(0); m_emitter->setEndSpinVar(0); m_emitter->setStartColor(Color4F(212, 73, 0, 1)); m_emitter->setStartColorVar(Color4F(0, 0, 0, 0)); m_emitter->setEndColor(Color4F(212, 73, 0, 1)); m_emitter->setEndColorVar(Color4F(0, 0, 0, 0)); m_emitter->setStartSize(20.0f); m_emitter->setStartSizeVar(0); m_emitter->setEndSize(15.0f); m_emitter->setEndSizeVar(0); m_emitter->setEmissionRate(275); m_emitter->setPosition(Vec2(player->getPosition().x, player->getPosition().y - 15)); addChild(m_emitter, 10); }
bool Hero::initAnimation() { bool bRet = false; do { auto spriteFrameCache = SpriteFrameCache::getInstance(); int frameNum = 0; //取几帧 int frameStart = 0;//起始number Vector<SpriteFrame *> actionVec; SpriteFrame *spriteFrame = nullptr; //------------------------------idle action 空闲---------------------- frameNum = 16; //取几帧 frameStart = 1;//起始number for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName( StringUtils::format("stand (%d).png", i)); actionVec.pushBack(spriteFrame); } idleAnimation = Animation::createWithSpriteFrames(actionVec, 0.04f); actionVec.clear(); CC_BREAK_IF(!idleAnimation); idleAnimation->retain(); //------------------------------run action 行走---------------------- frameNum = 20; //取几帧 frameStart = 1;//起始number for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName( StringUtils::format("walk (%d).png", i)); actionVec.pushBack(spriteFrame); } movingAnimation = Animation::createWithSpriteFrames(actionVec, 0.02f); actionVec.clear(); CC_BREAK_IF(!movingAnimation); movingAnimation->retain();//防止 动画被release掉,以至Role中方法调用动作报错 //------------------------------attack action 空闲---------------------- frameNum = 16; //取几帧 frameStart = 1;//起始number for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName( StringUtils::format("stand (%d).png", i)); actionVec.pushBack(spriteFrame); } attackAnimation = Animation::createWithSpriteFrames(actionVec, 0.04f); actionVec.clear(); CC_BREAK_IF(!attackAnimation); attackAnimation->retain(); bRet = true; } while (0); return bRet; }
MenuItemImage* createMenuItemImageWithSpriteFrame(const std::string& normalSpriteFrame, const std::string& selectedSpriteFrame, const std::string& disabledSpriteFrame, const ccMenuCallback& callback, Vec2 anchor, Vec2 pos){ auto item = MenuItemImage::create(); auto cache = CCSpriteFrameCache::getInstance(); item->setNormalSpriteFrame(cache->getSpriteFrameByName(normalSpriteFrame)); item->setSelectedSpriteFrame(cache->getSpriteFrameByName(selectedSpriteFrame)); item->setDisabledSpriteFrame(cache->getSpriteFrameByName(disabledSpriteFrame)); item->setCallback(callback); item->setAnchorPoint(anchor); item->setPosition(pos); item->setName(normalSpriteFrame); return item; }
ActionInterval * Carrot::doShakeOrBlink(int iImageFirstNumber, int iImageCount) { auto cache = SpriteFrameCache::getInstance(); Animation * pAnimation = Animation::create(); std::string sSpriteFrameName; for (int i = iImageFirstNumber; i < iImageFirstNumber + iImageCount; i++) { std::string sSpriteFrameName = _sName + StringUtils::format("%2d.png", i); pAnimation->addSpriteFrame(cache->getSpriteFrameByName(sSpriteFrameName)); } pAnimation->addSpriteFrame(cache->getSpriteFrameByName(_sModelName + PHOTOPOSTFIX)); pAnimation->setDelayPerUnit(0.1); pAnimation->setLoops(1); Animate * pAnimate = Animate::create(pAnimation); return pAnimate; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); auto cache=SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("anim.plist"); Vector<SpriteFrame*> vec; char name[15]; memset(name,0,15); for(int i=0;i<20;i++){ sprintf(name,"anim%04d",i); vec.pushBack(cache->getSpriteFrameByName(name)); } Animation *animation=Animation::createWithSpriteFrames(vec,0.1f); Animate *animate=Animate::create(animation); auto sprite=Sprite::create(); addChild(sprite); sprite->setPosition(200,200); sprite->runAction(RepeatForever::create(animate)); return true; }
Animation* CommonLib::genarelAnimation(const char* plistFile,const char* spriteFrameName,float delayPerUnit,int loopNum) { Animation* animation=AnimationCache::getInstance()->getAnimation(spriteFrameName); if (animation) return animation; auto spriteFrameCache=SpriteFrameCache::getInstance(); if (strlen(plistFile)>0) { spriteFrameCache->addSpriteFramesWithFile(plistFile); } int frameNum=10000; Vector<SpriteFrame*> arrayOfSpriteFrames; for (int i=1; i<frameNum; ++i) { char spriteFullName[64]={}; sprintf(spriteFullName, "%s%d.png",spriteFrameName,i); auto spriteFrame=spriteFrameCache->getSpriteFrameByName(spriteFullName); if (spriteFrame==nullptr) { // CCLOG("COMPLETE spriteFrame spriteFullName=%s",spriteFullName); break; } arrayOfSpriteFrames.pushBack(spriteFrame); } animation=Animation::createWithSpriteFrames(arrayOfSpriteFrames, delayPerUnit,loopNum); AnimationCache::getInstance()->addAnimation(animation, spriteFrameName); return animation; }
void Plane::initDestroyAction() { Animation *animation = Animation::create(); auto cache = SpriteFrameCache::getInstance(); animation->setDelayPerUnit(0.1f); animation->addSpriteFrame(cache->getSpriteFrameByName("hero_blowup_n1.png")); animation->addSpriteFrame(cache->getSpriteFrameByName("hero_blowup_n2.png")); animation->addSpriteFrame(cache->getSpriteFrameByName("hero_blowup_n3.png")); animation->addSpriteFrame(cache->getSpriteFrameByName("hero_blowup_n4.png")); Blink *blink = Blink::create(1,3); Animate *cc = Animate::create(animation); FiniteTimeAction *callback = CallFuncN::create(std::bind(planeIsDead, this)); m_destroyAction = (Sequence*)Sequence::create(cc, blink, callback, NULL); m_destroyAction->retain(); }
void Fly::deadAction() { //主机在死亡的时候会调用deadAction()方法 //先停止所有动作和定时器 stopAllActions(); unscheduleAllSelectors(); //制作主机死亡的动作 auto pAnimation = cocos2d::Animation::create(); auto pSpriteFrameCache = cocos2d::SpriteFrameCache::getInstance(); for (int i = 1; i <= FLY_BLOWUP_FRAME_COUNT; ++i) { pAnimation->addSpriteFrame(pSpriteFrameCache->getSpriteFrameByName(cocos2d::StringUtils::format("hero_blowup_%d.png", i))); } pAnimation->setDelayPerUnit(0.1f); pAnimation->setLoops(1); auto pAnimate = cocos2d::Animate::create(pAnimation); //制作主机死亡动作播放完成后的处理动作 auto pEnd = cocos2d::CallFunc::create([]() { SceneManager::getInstance()->changeScene(en_GameOverScene); CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(GAME_OVER); }); //将死亡动作和死亡处理动作串行处理 runAction(cocos2d::Sequence::create(pAnimate, pEnd, NULL)); }
bool Enemy::init_sprite(const Vec2 init_pos) { if (!Sprite::initWithFile(ENEMY_FILENAME)) return false; _speed_x = ENEMY_SPEED_X; this->setPosition(init_pos); // idle action auto frames_cache = SpriteFrameCache::getInstance(); frames_cache->addSpriteFramesWithFile("enemy_anim.plist"); auto sprite_sheet = SpriteBatchNode::create("enemy_anim.png"); this->addChild(sprite_sheet); std::string idle_frame_name; Vector<SpriteFrame *> idle_anim_frames; for (int i = 1; i <= 4; i++) { idle_frame_name = "enemy_idle_" + std::to_string(i) + ".png"; SpriteFrame *frame = frames_cache->getSpriteFrameByName(idle_frame_name); idle_anim_frames.pushBack(frame); } Animation *idle_animation = Animation::createWithSpriteFrames(idle_anim_frames, 0.25f); _idle = RepeatForever::create(Animate::create(idle_animation)); this->createWithSpriteFrameName("enemy_idle_1.png"); this->runAction(_idle); this->schedule(schedule_selector(Enemy::shoot), ENEMY_SHOOT_TIME); return true; }
bool CCActivityIndicator::init() { auto spritecache = SpriteFrameCache::getInstance(); spritecache->addSpriteFramesWithFile("ccactivityindicator.plist"); CCSpriteBatchNode::initWithFile("ccactivityindicator.png", 1); Size winSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); indicator = CCSprite::createWithSpriteFrameName("ccactivityindicator_1.gif"); indicator->setPosition(Vec2(winSize.width/2,winSize.height/2)); addChild(indicator); animating = false; hidesWhenStopped = true; // beginCallback = NULL; // endCallback = //load all sprite frames into array for (int i=1; i<=kActivityIndicatorFramesCount; i++) { SpriteFrame * frame = spritecache->getSpriteFrameByName(CCString::createWithFormat("ccactivityindicator_%d.gif",i)->getCString()); frame->retain(); spriteFrames.pushBack(frame); } return true; }
Vector<SpriteFrame*> HelloWorld::getAnimation(const char *format, int count) { auto spritecache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*> animFrames; char str[100]; for(int i = 0; i < count; i++) { sprintf(str, format, i); animFrames.pushBack(spritecache->getSpriteFrameByName(str)); } return animFrames; }
void AnimationManager::loadHeroAnimation(const char *plist) { auto cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(plist); auto animation = Animation::create(); for (int i = 1; i < 3; i++) { auto filename = StringUtils::format("mainplaneIdle%d.png", i); animation->addSpriteFrame(cache->getSpriteFrameByName(filename)); } animation->setDelayPerUnit(0.1f); animation->setLoops(-1); m_manager->addAnimation(animation, "hero-normal"); }
Animation* AnimationManager::getAnimationWithCacheNamed(char *format, USIZE nStart, USIZE nEnd) { auto cache = SpriteFrameCache::getInstance(); auto animation = Animation::create(); for (USIZE i = nStart; i <= nEnd; i++) { auto path = String::createWithFormat(format, i)->getCString(); auto frame = cache->getSpriteFrameByName(path); animation->addSpriteFrame(frame); } return animation; }
const std::tuple< std::vector<SpriteFrame*>, std::map<std::string, std::tuple<int, int> > >& CharacterDataPool::insert( const std::string& name, const std::string& foldername, const std::string& format) { auto already = _pool.find(name); if (already != end(_pool)) { return already->second; } rapidjson::Document json; Util::readJSON(foldername + "/" + name + "/data.json", json); std::vector<SpriteFrame*> animFrames; std::map<std::string, std::tuple<int, int> > actions; for (rapidjson::Value::MemberIterator M = json["actions"].MemberBegin(); M != json["actions"].MemberEnd(); M++) { std::string key = M->name.GetString(); actions.insert(std::make_pair(key, std::make_tuple(M->value["frameSize"].GetInt(), 0))); } auto frameCache = SpriteFrameCache::getInstance(); char number[10] = { 0 }; int accum = 0; for (std::map<std::string, std::tuple<int, int>>::iterator iter = begin(actions); iter != end(actions); iter++) { std::string filename = foldername + "/" + name + "/" + iter->first + ".plist"; frameCache->addSpriteFramesWithFile(filename); iter->second = std::make_tuple(std::get<0>(iter->second), accum); for (int i = 1; i <= DIRECTIONS * std::get<0>(iter->second); i++) { sprintf(number, "_%02d.", i); std::string tempstr = iter->first + number + format; auto frame = frameCache->getSpriteFrameByName(tempstr); animFrames.push_back(frame); } accum += std::get<0>(iter->second) * DIRECTIONS; } auto result = _pool.insert(std::make_pair(name, std::make_tuple(animFrames, actions))); return result.first->second; }
Sprite* CommonLayer::createBird() { auto cache = SpriteFrameCache::getInstance(); int randomIndex = rand()%3; std::string frameName = ""; Vector<SpriteFrame*> birdFrame; for (int i = 0; i < 3; i++) { frameName = "bird" + std::to_string(randomIndex) + "_" + std::to_string(i) + ".png"; auto frame = cache->getSpriteFrameByName(frameName); birdFrame.pushBack(frame); } auto bird = Sprite::createWithSpriteFrame(birdFrame.at(1)); auto animation = Animation::createWithSpriteFrames(birdFrame); animation->setDelayPerUnit(0.1); auto animate = Animate::create(animation); bird->runAction(RepeatForever::create(animate)); return bird; }
//阳关 void Bullet::createSunflashBullet(Point p, Layer *layer){ auto cache=SpriteFrameCache::getInstance(); char temp[50]="Sun_default.plist"; cache->addSpriteFramesWithFile("Sun_default.plist", "Sun_default.png"); this->initWithSpriteFrameName("Sun-1(被拖移).tiff"); this->setScale(0.4); __Dictionary *dic=__Dictionary::createWithContentsOfFile(temp); __Dictionary *dic2=(__Dictionary*)dic->objectForKey("frames"); int num=(int)dic2->allKeys()->count(); Vector<SpriteFrame *>vect; for ( int i=1; i<=num; i++) { std:: string str=StringUtils::format("Sun-%d(被拖移).tiff",i); auto frame=cache->getSpriteFrameByName(str); vect.pushBack(frame); } auto animation=Animation::createWithSpriteFrames(vect,0.1); auto animate=Animate::create(animation); this->runAction(RepeatForever::create(animate)); auto spriteItem=MenuItemSprite::create(this,this,[layer](Ref *sender){ auto sprite=static_cast<MenuItemSprite*>(sender); auto move=MoveTo::create(1, Vec2(55, 320)); auto call=CallFuncN::create([layer](Node *sen){ sen->removeFromParent(); //移除之后将获得lable的值进行相加+50 auto laye=(GameScene *)layer; auto lable=laye->lable; int a= atoi( lable->getString().c_str())+50; std::string str=StringUtils::format("%d",a); lable->setString(str); }); auto sequence=Sequence::create(move,call, NULL); auto menu= sprite->getParent(); menu->runAction(sequence); }); auto menu=Menu::create(spriteItem, NULL); menu->setPosition(p.x+20,p.y+25); layer->addChild(menu); auto jump=JumpTo::create(1, Vec2(p.x-5,p.y-5), 30, 1); menu->runAction(jump); }
void MenuScene::moveOver() { _moveOver = true; _tank = Sprite::createWithSpriteFrameName("player1_1_2_1.png"); this->addChild(_tank); this->setOption(ONE_PLAYER); Vector<SpriteFrame*> animFrames(2); auto cache = SpriteFrameCache::getInstance(); for (auto i = 1; i < 3; i++) { auto str = String::createWithFormat("player1_1_2_%d.png", i)->getCString(); auto frame = cache->getSpriteFrameByName(str); animFrames.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(animFrames, 0.01f); _tank->runAction(RepeatForever::create(Animate::create(animation))); }
bool Scale9Sprite::initWithSpriteFrameName(const std::string& spriteFrameName, const Rect& capInsets) { bool ret = false; do { auto spriteFrameCache = SpriteFrameCache::getInstance(); CCASSERT(spriteFrameCache != nullptr, "SpriteFrameCache::getInstance() must be non-NULL"); if(spriteFrameCache == nullptr) break; SpriteFrame *frame = spriteFrameCache->getSpriteFrameByName(spriteFrameName); CCASSERT(frame != nullptr, "CCSpriteFrame must be non-NULL"); if (frame == nullptr) break; ret = initWithSpriteFrame(frame, capInsets); } while (false); return ret; }
Animation* AnimationUtil::createAnimWithFrame(const char* name, float delay, int iLoops) { auto cache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*> framesArray = Vector<SpriteFrame*>(); SpriteFrame* frame = NULL; int index = 1; do { const char* tmp = String::createWithFormat("%s%d.png", name, index++)->getCString(); frame = cache->getSpriteFrameByName(tmp); if (frame == NULL) break; framesArray.pushBack(frame); } while (true); Animation* animation = Animation::createWithSpriteFrames(framesArray); animation->setLoops(iLoops); animation->setRestoreOriginalFrame(true); animation->setDelayPerUnit(delay); return animation; }
void Coin::onEnter() { Sprite::onEnter(); // super auto cacher = SpriteFrameCache::getInstance(); cacher->addSpriteFramesWithFile("parkour_img/background.plist"); Vector<SpriteFrame*> frames(8); for (int i = 0; i < 8; i++) { std::stringstream ss; ss << "coin" << i << ".png"; auto frame = cacher->getSpriteFrameByName(ss.str()); frames.pushBack(frame); } auto anim = Animation::createWithSpriteFrames(frames, 0.1f); auto action = Animate::create(anim); auto anime = RepeatForever::create(action); this->runAction(anime); }
void SpriteFrameCacheHelper::retainSpriteFrames(const std::string &plistPath) { auto it = _usingSpriteFrames.find(plistPath); if(it != _usingSpriteFrames.end()) return; std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plistPath); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); auto spriteFramesCache = SpriteFrameCache::getInstance(); ValueMap& framesDict = dict["frames"].asValueMap(); std::vector<SpriteFrame*> vec; for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter) { auto& spriteFrameName = iter->first; SpriteFrame* spriteFrame = spriteFramesCache->getSpriteFrameByName(spriteFrameName); vec.push_back(spriteFrame); CC_SAFE_RETAIN(spriteFrame); } _usingSpriteFrames[plistPath] = vec; }
void Skill::thunder() { log("thunder..."); Player* player = Player::getInstance(); if (!player->getThundering()) { player->thunder(); auto animationCache = AnimationCache::getInstance(); // check if already loaded auto animation = animationCache->getAnimation("skill_thunder"); if (!animation) { auto spriteFrameCache = SpriteFrameCache::getInstance(); animation = Animation::create(); animation->setDelayPerUnit(0.1f); //put frames into animation for (int i = 0; i < 8; i++) { animation->addSpriteFrame(spriteFrameCache->getSpriteFrameByName(String::createWithFormat("thunder_%d.png", i)->getCString())); } // put the animation into cache animationCache->addAnimation(animation, "skill_thunder"); } float x = (SIZE_WIDTH - 100) / 6; float y = (SIZE_HEIGHT - 80) / 8; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { Sprite* thunder = Sprite::createWithSpriteFrameName("thunder_0.png"); thunder->setPosition(50 + x * (i * 2 + 1), 40 + y * (j * 2 + 1)); thunder->setRotation(15); this->getParent()->addChild(thunder); _thunders.pushBack(thunder); thunder->runAction(Sequence::create(Repeat::create(Animate::create(animation), 10), CallFuncN::create(CC_CALLBACK_1(Skill::thunderEnd, this)), NULL)); } } this->getParent()->schedule(CC_CALLBACK_1(Skill::thundering, this), 1, "thudering"); } }
Animation* AnimationManager::getImageAnimationWithPlist(char *plist, char *format, USIZE nStart, USIZE nEnd, char *imagePath) { auto cache = SpriteFrameCache::getInstance(); if (imagePath) cache->addSpriteFramesWithFile(plist, imagePath); else cache->addSpriteFramesWithFile(plist); auto animation = Animation::create(); animation->retain(); for (USIZE i = nStart; i <= nEnd; ++i) { auto path = String::createWithFormat(format, i)->getCString(); auto frame = cache->getSpriteFrameByName(path); animation->addSpriteFrame(frame); } return animation; }
Animation* Character::createAnimationPlist(const std::string plist, const char* spriteName, int numberOfSprites, float delay) { auto cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(plist); Vector<SpriteFrame*> animFrames; char str[100] = { 0 }; for (int i = 1; i < numberOfSprites; i++) { sprintf(str, spriteName, i); SpriteFrame* frame = cache->getSpriteFrameByName(str); animFrames.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(animFrames, delay); return animation; }
Animation* GameUtils::getAnimationByKeyAndFrameName(const std::string& aniKey, const std::string& frameName, const int& frameCount, float delay){ auto animCache = AnimationCache::getInstance(); auto resultAnimation = animCache->getAnimation(aniKey); if( resultAnimation == nullptr){ auto frameCache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*> animFrames(frameCount); char str[50] = {0}; for(int i = 0; i < frameCount; i++){ sprintf(str, frameName.c_str(),i); auto frame = frameCache->getSpriteFrameByName(str); CCASSERT(frame != nullptr, "frame is null!"); animFrames.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(animFrames, delay); // Add an animation to the Cache AnimationCache::getInstance()->addAnimation(animation, aniKey); animFrames.clear(); resultAnimation = animCache->getAnimation(aniKey); //log("no cache"); } return resultAnimation; }
bool AirPlane::initAnimation() { auto spriteFrameCache = SpriteFrameCache::getInstance(); int frameNum = 0; int frameStart = 0; Vector<SpriteFrame *>actionVec; SpriteFrame *spriteFrame = nullptr; //------------------------------idle action–---------------------- frameNum = 4; frameStart = 0; for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName(StringUtils::format("pet2_%d.png", i)); actionVec.pushBack(spriteFrame); } auto idleAnimation = Animation::createWithSpriteFrames(actionVec, 0.03f); actionVec.clear(); idleAnimation->retain(); this->setIdleAnimation(idleAnimation); //------------------------------run action---------------------- frameNum = 4; frameStart = 0; for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName(StringUtils::format("pet2_%d.png", i)); actionVec.pushBack(spriteFrame); } auto movingAnimation = Animation::createWithSpriteFrames(actionVec, 0.03f); actionVec.clear(); movingAnimation->retain(); this->setMovingAnimation(movingAnimation); //-----------------------------attack action--------------------------- frameNum = 4; frameStart = 0; for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName(StringUtils::format("pet2_%d.png", i)); actionVec.pushBack(spriteFrame); } auto attackAnimation = Animation::createWithSpriteFrames(actionVec, 0.03f); actionVec.clear(); attackAnimation->retain(); this->setAttackAnimation(attackAnimation); //-----------------------------hurt action--------------------------- frameNum = 4; frameStart = 0; for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName(StringUtils::format("pet2_%d.png", i)); actionVec.pushBack(spriteFrame); } auto hurtAnimation = Animation::createWithSpriteFrames(actionVec, 0.03f); actionVec.clear(); hurtAnimation->retain(); this->setHurtAnimation(hurtAnimation); //-----------------------------dead action--------------------------- frameNum = 4; frameStart = 0; for (int i = frameStart; i < frameNum; i++){ spriteFrame = spriteFrameCache->getSpriteFrameByName(StringUtils::format("pet2_%d.png", i)); actionVec.pushBack(spriteFrame); } auto deadAnimation = Animation::createWithSpriteFrames(actionVec, 0.03f); actionVec.clear(); deadAnimation->retain(); this->setDeadAnimation(deadAnimation); return true; }
FiniteTimeAction* AnimationController::getActionFromAnimationData(AnimationData tmpData) { FiniteTimeAction* ac; if (tmpData.getStyleId() == "move") { ac = MoveTo::create(tmpData.getDuration(), tmpData.getEndPosition()); } else if (tmpData.getStyleId() == "moveby") { ac = MoveBy::create(tmpData.getDuration(), tmpData.getEndPosition()); } else if (tmpData.getStyleId() == "rotate") { ac = RotateTo::create(tmpData.getDuration(), tmpData.getAngle()); } else if (tmpData.getStyleId() == "rotateby") { ac = RotateBy::create(tmpData.getDuration(), tmpData.getAngle()); } else if (tmpData.getStyleId() == "scale") { ac = ScaleTo::create(tmpData.getDuration(), tmpData.getScale()); } else if (tmpData.getStyleId() == "scaleby") { ac = ScaleBy::create(tmpData.getDuration(), tmpData.getScale()); } else if (tmpData.getStyleId() == "jump") { ac = JumpTo::create(tmpData.getDuration(), tmpData.getEndPosition(), tmpData.getHeight(), tmpData.getJumps()); } else if (tmpData.getStyleId() == "jumpby") { ac = JumpBy::create(tmpData.getDuration(), tmpData.getEndPosition(), tmpData.getHeight(), tmpData.getJumps()); } else if (tmpData.getStyleId() == "blink") { ac = Blink::create(tmpData.getDuration(), tmpData.getBlinks()); } else if (tmpData.getStyleId() == "tint") { ac = TintTo::create(tmpData.getDuration(), tmpData.getRGBColor().r, tmpData.getRGBColor().g, tmpData.getRGBColor().b); } else if (tmpData.getStyleId() == "tintby") { ac = TintBy::create(tmpData.getDuration(), tmpData.getRGBColor().r, tmpData.getRGBColor().g, tmpData.getRGBColor().b); } else if (tmpData.getStyleId() == "fade") { ac = FadeTo::create(tmpData.getDuration(), tmpData.getOpacity()); } else if (tmpData.getStyleId() == "delaytime") { ac = DelayTime::create(tmpData.getDelay()); } else if (tmpData.getStyleId() == "bezier") { ccBezierConfig bezier; bezier.controlPoint_1 = tmpData.getBezierPointOne(); bezier.controlPoint_2 = tmpData.getBezierPointTwo(); bezier.endPosition = tmpData.getEndPosition(); ac = BezierTo::create(tmpData.getDuration(), bezier); } else if (tmpData.getStyleId() == "bezierby") { ccBezierConfig bezier; bezier.controlPoint_1 = tmpData.getBezierPointOne(); bezier.controlPoint_2 = tmpData.getBezierPointTwo(); bezier.endPosition = tmpData.getEndPosition(); ac = BezierBy::create(tmpData.getDuration(), bezier); } else if (tmpData.getStyleId() == "place") { ac = Place::create(tmpData.getPosition()); } else if (tmpData.getStyleId() == "scaleXY") { auto ac1 = ScaleTo::create(tmpData.getDuration(), tmpData.getScaleX(), tmpData.getScaleY()); auto ac2 = ScaleTo::create(tmpData.getDuration(), 1.0f, 1.0f); ac = Sequence::create(ac1,ac2, NULL); } else if (tmpData.getStyleId() == "scaleXYby") { auto ac1 = ScaleTo::create(tmpData.getDuration(), tmpData.getScaleX(), tmpData.getScaleY()); auto ac2 = ScaleTo::create(tmpData.getDuration(), 1, 1); ac = Sequence::create(ac1,ac2, NULL); } else if (tmpData.getStyleId() == "rotateXY") { ac = RotateTo::create(tmpData.getDuration(), tmpData.getAngleX(), tmpData.getAngleY()); } else if (tmpData.getStyleId() == "rotateXYby") { ac = RotateBy::create(tmpData.getDuration(), tmpData.getAngleX(), tmpData.getAngleY()); } else if (tmpData.getStyleId() == "diyrotateby") { //圆周运动,暂时未添加 } else if (tmpData.getStyleId() == "hide") { ac = Hide::create(); } else if (tmpData.getStyleId() == "show") { ac = Show::create(); } else if (tmpData.getStyleId() == "EaseIn") { //暂时未添加 } else if (tmpData.getStyleId() == "EaseOut") { //暂时未添加 } else if (tmpData.getStyleId() == "animation") { int count = tmpData.getFramecount(); auto cache = SpriteFrameCache::getInstance(); //获取图片名称 string sImageName = tmpData.getImageId(); unsigned long pos = sImageName.find("0000.png"); sImageName.replace(pos, 8, ""); Vector<SpriteFrame*> vSpreiteFrame; char str[50] = {0}; for(int i = 0; i <count; i++) { sprintf(str, "%s000%d.png",sImageName.c_str(),i); //加载精灵帧 auto frame = cache->getSpriteFrameByName(str); vSpreiteFrame.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(vSpreiteFrame,0.4f); ac = Animate::create(animation); } return ac; }
bool WelcomeScene::init() { if (!Layer::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("image/all_pic.plist"); bgLayer = BgLayer::create(); bgLayer->removeChildByTag(BgLayer::TimeTag); bgLayer->removeChildByTag(BgLayer::ProgressTag); bgLayer->removeChildByTag(BgLayer::ProgressBgtag); this->addChild(bgLayer); menuLayer = MenuLayer::create(); this->addChild(menuLayer); // 标题 auto titleLabel = Label::createWithTTF("Meteorite Crisis", "fonts/Marker Felt.ttf", 60); titleLabel->setPosition(visibleSize.width / 2, visibleSize.height * 0.8); addChild(titleLabel); //menu play auto one_man = MenuItemImage::create(); auto normal1 = SpriteFrameCache::getInstance()->getSpriteFrameByName("one_man_normal.png"); auto selected1 = SpriteFrameCache::getInstance()->getSpriteFrameByName("one_man_clicked.png"); one_man->setNormalSpriteFrame(normal1); one_man->setSelectedSpriteFrame(selected1); one_man->setCallback([](Ref*){ auto s = GameScene::createScene(); float t = 0.5f; struct timeval psv; gettimeofday(&psv, NULL); unsigned rand_seed = (unsigned)(psv.tv_sec + psv.tv_usec); //转化为毫秒 srand(rand_seed); float choice = rand_0_1(); if (choice < 0.25) { Director::getInstance()->replaceScene(TransitionFlipY::create(t, s)); } else if (choice >= 0.25 && choice < 0.5) { Director::getInstance()->replaceScene(TransitionFlipY::create(t, s)); } else if (choice >= 0.5 && choice < 0.75) { Director::getInstance()->replaceScene(TransitionProgressRadialCCW::create(t, s)); } else if (choice >= 0.75 && choice < 1.0) { Director::getInstance()->replaceScene(TransitionProgressRadialCW::create(t, s)); } }); one_man->setScale(0.5f); //menu how to play auto howToPlay = MenuItemImage::create(); auto normal2 = SpriteFrameCache::getInstance()->getSpriteFrameByName("howtoplay_normal.png"); auto selected2 = SpriteFrameCache::getInstance()->getSpriteFrameByName("howtoplay_clicked.png"); howToPlay->setNormalSpriteFrame(normal2); howToPlay->setSelectedSpriteFrame(selected2); howToPlay->setCallback([&,this](Ref*){ auto s = HowToPlay::createScene(); float t = 0.5f; struct timeval psv; gettimeofday(&psv, NULL); unsigned rand_seed = (unsigned)(psv.tv_sec + psv.tv_usec); //转化为毫秒 srand(rand_seed); float choice = rand_0_1(); if (choice < 0.25) { Director::getInstance()->replaceScene(TransitionFlipY::create(t, s)); } else if (choice >= 0.25 && choice < 0.5) { Director::getInstance()->replaceScene(TransitionFlipY::create(t, s)); } else if (choice >= 0.5 && choice < 0.75) { Director::getInstance()->replaceScene(TransitionProgressRadialCCW::create(t, s)); } else if (choice >= 0.75 && choice < 1.0) { Director::getInstance()->replaceScene(TransitionProgressRadialCW::create(t, s)); } }); howToPlay->setScale(0.5f); howToPlay->setPositionY(- howToPlay->getContentSize().height/2 - 5); auto menu = Menu::create(one_man, howToPlay, NULL); menu->setPosition(visibleSize.width / 2, visibleSize.height * 0.5); menu->setAnchorPoint(Vec2(0.5,1)); addChild(menu); // 主角模型 auto player = Sprite::createWithSpriteFrameName("SpaceFlier4.png"); player->setScale(0.5); player->setPosition(visibleSize.width/2, visibleSize.height * 0.65); auto cache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*> vec_sf; SpriteFrame* sf = NULL; for (int i = 1; i <= 5; ++i) { sf = cache->getSpriteFrameByName(StringUtils::format("SpaceFlier%d.png", i)); vec_sf.pushBack(sf); } Animation* animation = Animation::createWithSpriteFrames(vec_sf, 0.05f, -1); auto action = Animate::create(animation); player->runAction(CCRepeatForever::create( Sequence::create(action, action->reverse(), NULL))); addChild(player); // 最高分 // 最高分标题 auto highScoreTitle = Label::createWithTTF("BestScore:", "fonts/Marker Felt.ttf", 25); highScoreTitle->setPosition(visibleSize.width * 0.48, visibleSize.height * 0.2); this->addChild(highScoreTitle); // 最高分 auto bestScore = UserDefault::getInstance()->getIntegerForKey("highScore"); auto highScore = Label::createWithTTF( __String::createWithFormat("%i", bestScore)->getCString(), "fonts/Marker Felt.ttf", 25); highScore->setPosition(visibleSize.width * 0.6 , visibleSize.height * 0.2); this->addChild(highScore); return true; }