//INITS void GameScreen::InitAnimation() { SpriteBatchNode* spritebatch = SpriteBatchNode::create("Assets/Animation/Idle.png"); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("Assets/Animation/Idle.plist"); _santaPaused = Sprite::createWithSpriteFrameName("Assets/Santa/idle_0001.png"); spritebatch->addChild(_santaPaused); addChild(spritebatch); _santaPaused->setPosition(Vec2(-_winSizeW*0.5f, _winSizeH*0.7f)); Vector<SpriteFrame*> animFrames; char str[100] = { 0 }; for (int i = 1; i <= 12; i++) { sprintf(str, "Assets/Santa/idle_%04d.png", i); SpriteFrame* frame = cache->getSpriteFrameByName(str); animFrames.pushBack(frame); } Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); _santaPaused->runAction(RepeatForever::create(Animate::create(animation))); }
bool HeroPlane::init(){ Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("heroplane.plist", "heroplane.png");//加载全局资源 plane = Sprite::createWithSpriteFrameName("plane1.png");//生成飞机 plane->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 5)); this->addChild(plane, 0, 1); Blink *blink = Blink::create(3,8);//闪烁动画 Animation* animation = Animation::create(); animation->setDelayPerUnit(0.1f); animation->addSpriteFrame(frameCache->getSpriteFrameByName("plane1.png")); animation->addSpriteFrame(frameCache->getSpriteFrameByName("plane2.png")); Animate* animate = Animate::create(animation);//帧动画 plane->runAction(blink);//执行闪烁动画 plane->runAction(RepeatForever::create(animate));// 执行帧动画 //开启触摸事件,让飞机跟随手指移动 auto listen = EventListenerTouchOneByOne::create(); listen->onTouchBegan = CC_CALLBACK_2(HeroPlane::onTouchBegan, this); listen->onTouchMoved = CC_CALLBACK_2(HeroPlane::onTouchMoved, this); listen->onTouchEnded = CC_CALLBACK_2(HeroPlane::onTouchEened, this); listen->onTouchCancelled = CC_CALLBACK_2(HeroPlane::onTouchCancelled, this); listen->setSwallowTouches(false); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listen, this); return true; }
void XHelper::runAnimation(string name, int count, float time, bool isRepeat, Sprite* _sprite) { if (_sprite != nullptr) { _sprite->getActionManager()->removeAllActionsFromTarget(_sprite); //CCLOG(&name[0]); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(name + ".plist"); //Chuyển thành sprite frame Animation* animation = Animation::create(); animation->setDelayPerUnit(time); char frameName[100]; for (int i = 1; i <= count; i++) { sprintf(frameName, "%s%d.png", &name[0], i); //CCLOG("framename : %s", frameName); auto frame = cache->getSpriteFrameByName(frameName); animation->addSpriteFrame(frame); } Action* action = nullptr; if (isRepeat) action = RepeatForever::create(Animate::create(animation)); else action = Animate::create(animation); _sprite->runAction(action); } else{ log("XHelper::runAnimation : _sprite iss null"); } }
void ShopLayer::RefreshShopList(Ref*pSender) { if (shadow->isVisible()) { shadow->setVisible(false); } int _count = UserProfile::instance()->GetShopItemCount(); rongqi = Widget::create(); SpriteFrameCache * cache = SpriteFrameCache::getInstance(); for (auto i = 0; i < SHOPITEMNUM; i++) { CAKE = CSLoader::createNode("shop_info.csb"); CAKE->setPosition(Vec2(i % 3* 230 + 75, (-i/3*180) + 262)); CAKE->setTag(i); auto pro_id_btn = dynamic_cast<Button*>(CAKE->getChildByName("shop_id_01_node")->getChildByTag(1)); pro_id_btn->setTag(i+1); goods_name = dynamic_cast<Text*>(CAKE->getChildByName("shop_id_01_node")->getChildByName("Text")); goods_name->setTag(i); goods_price = dynamic_cast<Text*>(CAKE->getChildByName("shop_id_01_node")->getChildByName("coin_num_text")); goods_price->setTag(i); goods_level = dynamic_cast<Text*>(CAKE->getChildByName("shop_id_01_node")->getChildByName("Cur_lev")); goods_level->setTag(i); String * str_shop_id = String::createWithFormat("shop_id_%02d", i + 1); int cur_level = UserProfile::instance()->GetShopItemLevel(i); pro_id_btn->addClickEventListener(CC_CALLBACK_1(ShopLayer::BuyProp, this)); goods_isheigh = dynamic_cast<Text*>(CAKE->getChildByName("shop_id_01_node")->getChildByName("Heigh_Lev")); goods_isheigh->setVisible(false); int test = atoi(goods_level->getString().c_str()); switch (i) { case 0: case 2: case 3: if (cur_level == 2) { goods_isheigh->setVisible(true); pro_id_btn->setEnabled(false); cur_level = 1; } break; default: if (cur_level == 3) { goods_isheigh->setVisible(true); pro_id_btn->setEnabled(false); cur_level = 2; } break; } goods_name->setString(Json::getInstance()->getJson("ITEM", i, str_shop_id->getCString(), "ITEM_NAME", cur_level)); goods_price->setString(Json::getInstance()->getJson("ITEM", i, str_shop_id->getCString(), "ITEM_SOLD_PRICE", cur_level)); goods_level->setString(Json::getInstance()->getJson("ITEM", i, str_shop_id->getCString(), "ITEM_LEVEL", cur_level)); std::string sp_name = Json::getInstance()->getJson("ITEM", i, str_shop_id->getCString(), "ITEM_IMAGE", cur_level); sp_image = dynamic_cast<Sprite*>(CAKE->getChildByName("shop_id_01_node")->getChildByName("sp_image")); sp_image->setDisplayFrame(cache->getSpriteFrameByName(sp_name)); rongqi->addChild(CAKE); } item_layout->addChild(rongqi); }
Sprite* CTextRich::makeAnim( Sprite* pTarget,RenderElement elem ) { SpriteFrameCache *pCache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*> v; SpriteFrame *pFrame = NULL; int index = 1; char buf[128] = {0}; do { sprintf(buf,"%s%d.png",elem.anim.c_str(),index++); pFrame = pCache->getSpriteFrameByName(buf); if(pFrame == NULL){ break; } v.pushBack(pFrame); } while (true); Animation *pAnim = Animation::createWithSpriteFrames(v); pAnim->setLoops(elem.isLoop?-1:0); pAnim->setRestoreOriginalFrame(true); pAnim->setDelayPerUnit(elem.delay); pTarget->setContentSize(v.at(0)->getOriginalSize()); pTarget->stopAllActions(); pTarget->runAction(Animate::create(pAnim)); pTarget->setUserData( elem.data != "" ? new std::string(elem.data) : nullptr ); return pTarget; }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto background = Sprite::create("background.png");//加载背景精灵 background->setAnchorPoint(Vec2::ZERO); this->addChild(background,0); SpriteFrameCache *frameCache = SpriteFrameCache::getInstance();//单例对象 frameCache->addSpriteFramesWithFile("SpriteSheet.plist");//加载精灵图集 auto mountain1 = Sprite::createWithSpriteFrameName("mountain1.png");//通过精灵帧名创建精灵 mountain1->setAnchorPoint(Vec2::ZERO);//设置锚点 mountain1->setPosition(Vec2(-200,80)); this->addChild(mountain1,0); SpriteFrame *heroSpriteFrame = frameCache->getSpriteFrameByName("hero1.png");//通过精灵帧名字获取精灵帧 Sprite *hero1 = Sprite::createWithSpriteFrame(heroSpriteFrame);//通过精灵帧创建精灵 //上面的两条语句相当于前面一条语句的效果auto mountain1 = Sprite::createWithSpriteFrameName("mountain1.png"); hero1->setPosition(Vec2(800,200)); this->addChild(hero1,0); return true; }
bool WalkerLayer::init() { if (!Layer::init()) { CCLOG("Error in init WalkerLayer!"); return false; } float screenWidth = Director::getInstance()->getVisibleSize().width; SpriteFrameCache *cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(WALKER_PLIST_PATH, WALKER_TEXTURE_PATH); char frameName[30]; Sprite *walker = Sprite::create(); walker->setAnchorPoint(Vec2(0.5f, 0.0f)); walker->setPosition(Vec2(screenWidth * 0.5, _vPos)); addChild(walker, 0, "walker"); Animation *walkAnimation = Animation::create(); for (int i = 1; i <= _frameCount; ++i) { sprintf_s(frameName, 20, "%s%d.png", _name.c_str(), i); walkAnimation->addSpriteFrame(cache->getSpriteFrameByName(frameName)); } for (int i = _frameCount; i > 1; --i) { sprintf_s(frameName, 20, "%s%d.png", _name.c_str(), i); walkAnimation->addSpriteFrame(cache->getSpriteFrameByName(frameName)); } walkAnimation->setLoops(-1); walkAnimation->setRestoreOriginalFrame(false); walkAnimation->setDelayPerUnit(0.2f); walker->runAction(RepeatForever::create(Animate::create(walkAnimation))); return true; }
KDvoid SampleLayer::addCharacter ( KDvoid ) { // plist 에서 달리기 애니매이션 로딩 SpriteFrameCache* pFrameCache = SpriteFrameCache::getInstance ( ); pFrameCache->addSpriteFramesWithFile ( "ch01.plist" ); Dictionary* pDictionary = Dictionary::createWithContentsOfFile ( "ch01_1_aniinfo.plist" ); Array* pAnimationList = (Array*) pDictionary->objectForKey ( "animationlist" ); Array* pFrameList = (Array*) pDictionary->objectForKey ( "framelist" ); String* pName = (String*) pDictionary->objectForKey ( "name" ); String* pTexture = (String*) pDictionary->objectForKey ( "texture" ); String* pType = (String*) pDictionary->objectForKey ( "type" ); Dictionary* pAnimationItem = (Dictionary*) pAnimationList->getObjectAtIndex ( 12 ); Array* pTemp = (Array*) pAnimationItem->objectForKey ( "FrameList" ); KDfloat fTemp = ( (String*) pAnimationItem->objectForKey ( "FPS" ) )->floatValue ( ); Array* pArraySpriteFrame = Array::createWithCapacity ( pTemp->count ( ) ); Animation* pAnimation = Animation::create ( ); for ( KDint32 i = 0; i < pTemp->count ( ); i++ ) { KDint ii = ( (String*) pTemp->getObjectAtIndex ( i ) )->intValue ( ); String* pString = (String*) pFrameList->getObjectAtIndex ( ii ); pAnimation->addSpriteFrame ( pFrameCache->getSpriteFrameByName ( pString->getCString ( ) ) ); } pAnimation->setDelayPerUnit ( fTemp ); Sprite* pSprite = Sprite::createWithSpriteFrameName ( ( (String*) pFrameList->getObjectAtIndex ( 21 ) )->getCString ( ) ); Point tPoint = Point ( Point ( 100, 200 ) ); Point tOffset = pSprite->getDisplayFrame ( )->getOffset ( ); pSprite->setPosition ( tPoint - tOffset ); pSprite->runAction ( RepeatForever::create ( Animate::create ( pAnimation ) ) ); pSprite->setTag ( 10 ); this->addChild ( pSprite ); // Box2D body setting b2BodyDef tBodyDef; tBodyDef.type = b2_dynamicBody; tBodyDef.position.Set ( tPoint.x / PTM_RATIO, tPoint.y / PTM_RATIO ); tBodyDef.userData = pSprite; b2PolygonShape tDynamicBox; Size tSize = pSprite->getDisplayFrame ( )->getRect ( ).size; tDynamicBox.SetAsBox ( tSize.width / 2 / PTM_RATIO, tSize.height / 2 / PTM_RATIO ); m_pBody = m_pWorld->CreateBody ( &tBodyDef ); b2FixtureDef tFixtureDef; tFixtureDef.shape = &tDynamicBox; tFixtureDef.density = 1.0f; tFixtureDef.friction = 0.0f; m_pBody->CreateFixture ( &tFixtureDef ); }
bool StartLayer::init() { bool ret = false; do { CC_BREAK_IF(!Layer::init()); Size s = Director::getInstance()->getWinSize(); SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("ui/shoot_background.plist", "ui/shoot_background.png"); frameCache->addSpriteFramesWithFile("ui/shoot.plist"); Sprite *backGround = Sprite::createWithSpriteFrameName("background.png"); backGround->setPosition(Point(s.width * 0.5, s.height * 0.5)); addChild(backGround, -1, 0); Sprite *title = Sprite::createWithSpriteFrameName("shoot_copyright.png"); title->setPosition(Point(s.width * 0.5, s.height * 2 / 3)); addChild(title, 0, 1); Sprite *gameLoad = Sprite::createWithSpriteFrameName(LOADIMAGE[0].c_str()); gameLoad->setPosition(Point(s.width * 0.5, s.height * 0.5)); addChild(gameLoad, 0, 2); Animation* animation = Animation::create(); animation->setDelayPerUnit(0.4f); animation->addSpriteFrame(frameCache->getSpriteFrameByName(LOADIMAGE[0].c_str())); animation->addSpriteFrame(frameCache->getSpriteFrameByName(LOADIMAGE[1].c_str())); animation->addSpriteFrame(frameCache->getSpriteFrameByName(LOADIMAGE[2].c_str())); animation->addSpriteFrame(frameCache->getSpriteFrameByName(LOADIMAGE[3].c_str())); Animate* animate = Animate::create(animation); gameLoad->runAction(RepeatForever::create(animate)); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchEnded = [](Touch *touch, Event *event) { Scene *st = Scene::create(); BackgroundLayer *back = BackgroundLayer::create(); st->addChild(back); GameLayer *gameLayer = GameLayer::create(); st->addChild(gameLayer); Director::getInstance()->replaceScene(st); return; }; touchListener->onTouchMoved = [](Touch* touch, Event* event){ return; }; touchListener->onTouchBegan = [](Touch *touch, Event *event) { return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); ret = true; } while (0); return ret; }
void Sprite::setSpriteFrame(const std::string &spriteFrameName) { SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName); CCASSERT(spriteFrame, std::string("Invalid spriteFrameName :").append(spriteFrameName).c_str()); setSpriteFrame(spriteFrame); }
void Sprite::setSpriteFrame(const std::string &spriteFrameName) { SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName); CCASSERT(spriteFrame, "Invalid spriteFrameName"); setSpriteFrame(spriteFrame); }
bool PlayLayer::init() { if(!BaseLayer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); MenuItemFont *back = MenuItemFont::create("back", CC_CALLBACK_1(PlayLayer::back, this)); Menu *menu = Menu::create(back, NULL); menu->setPosition(visibleSize.width*9/10, visibleSize.height*9/10); this->addChild(menu); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("UI.plist", "UI.png"); mJoystick = NULL; mJoystick = new SneakyJoystick(); mJoystick->initWithRect(Rect::ZERO); mJoystick->setAutoCenter(true); mJoystick->setHasDeadzone(true); mJoystick->setDeadRadius(10); SneakyJoystickSkinnedBase* jstickSkin = new SneakyJoystickSkinnedBase(); jstickSkin->autorelease(); jstickSkin->init(); jstickSkin->setBackgroundSprite(CCSprite::createWithSpriteFrameName("JoyStick-base.png")); jstickSkin->setThumbSprite(CCSprite::createWithSpriteFrameName("JoyStick-thumb.png")); //jstickSkin->getThumbSprite()->setScale(0.5f); jstickSkin->setPosition(visibleSize.width*1/10, visibleSize.width*1/10); jstickSkin->setJoystick(mJoystick); this->addChild(jstickSkin); mButtonA = NULL; mButtonA = new SneakyButton(); mButtonA->initWithRect(Rect::ZERO); mButtonA->setIsToggleable(false); mButtonA->setIsHoldable(true); SneakyButtonSkinnedBase* btnASkin = new SneakyButtonSkinnedBase(); btnASkin->autorelease(); btnASkin->init(); btnASkin->setPosition(visibleSize.width*9/10, visibleSize.width*1/10); btnASkin->setDefaultSprite(CCSprite::createWithSpriteFrameName("button-default.png")); btnASkin->setPressSprite(CCSprite::createWithSpriteFrameName("button-pressed.png")); btnASkin->setActivatedSprite(CCSprite::createWithSpriteFrameName("button-activated.png")); //btnASkin->setDisabledSprite(CCSprite::createWithSpriteFrameName("button-disabled.png")); btnASkin->setButton(mButtonA); this->addChild(btnASkin); this->schedule(schedule_selector(PlayLayer::inputUpdate)); startPlay(); return true; }
Vector<SpriteFrame*>* Face::createFrameVector(const std::string& patternName, int startFrame, int endFrame) { SpriteFrameCache *spriteFrameCache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*>*framesVector = new Vector<SpriteFrame*>; char frameName[128]; for(int i = startFrame; i <= endFrame; i++){ sprintf(frameName, patternName.c_str(), i); framesVector->pushBack(spriteFrameCache->getSpriteFrameByName(frameName)); } return framesVector; }
Tank* Tank::createTankWithTankType(const char* tankTypeName, TileMapInfo* tileMapInfo) { SpriteFrameCache* pCache = SpriteFrameCache::getInstance(); pCache->addSpriteFramesWithFile("tank.plist"); Tank* tank = new Tank(); tank->initTankWithTankType(tankTypeName, tileMapInfo); tank->autorelease(); return tank; }
void Pipe::addPipe(float dt) { SpriteFrameCache *pFrameCache = SpriteFrameCache::getInstance(); auto pipe_up = Sprite::createWithSpriteFrame(pFrameCache->getSpriteFrameByName("pipe_up.png")); pipe_up->setPosition(Point(pipe_up->getContentSize().width/2,pipe_up->getContentSize().height/2)); auto body_up=PhysicsBody::create(); auto body_shape_up=PhysicsShapeBox::create(pipe_up->getContentSize()); body_up->addShape(body_shape_up); body_up->setDynamic(false); body_up->setGravityEnable(false); body_up->setCategoryBitmask(1); body_up->setCollisionBitmask(-1); body_up->setContactTestBitmask(-1); pipe_up->setPhysicsBody(body_up); //向下管道初始化,这边的THROUGH_HEIGHT是两根管道之间的空隙 auto pipe_down = Sprite::createWithSpriteFrame(pFrameCache->getSpriteFrameByName("pipe_down.png")); pipe_down->setPosition(Point(pipe_down->getContentSize().width/2,pipe_down->getContentSize().height/2+pipe_up->getContentSize().height+THROUGH_HEIGHT)); auto body_down=PhysicsBody::create(); auto body_shape_down=PhysicsShapeBox::create(pipe_down->getContentSize()); body_down->addShape(body_shape_down); body_down->setDynamic(false); body_down->setGravityEnable(false); body_down->setCategoryBitmask(1); body_down->setCollisionBitmask(-1); body_down->setContactTestBitmask(-1); pipe_down->setPhysicsBody(body_down); //这边的node相当于一个容器把这两个管道封装在一个节点中并设置target auto node=Node::create(); node->addChild(pipe_up,0,PIPE_UP); node->addChild(pipe_down,0,PIPE_DOWN); node->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); //关于管道Y坐标的设置(就是管道上下长度不一样的处理),大家还是看图例,说不清楚 //管道是从右边移动到左边,所以PIPE_X的值肯定比游戏的width要大这里设定是300 int range=rand()%PIPE_RANGE; node->setPosition(Point(PIPE_X, PIPE_Y + range)); ActionManager *pActionManager = Director::getInstance()->getActionManager(); MoveBy *pMoveBy = MoveBy::create(3.2f, Point(-400, 0)); CallFuncN *pMoveOverCallback = CallFuncN::create(CC_CALLBACK_1(Pipe::moveOverHandle, this)); ActionInterval *pSeq = Sequence::create(pMoveBy, pMoveOverCallback, nullptr); pActionManager->addAction(pSeq, node, false); this->addChild(node); pPipeVector.pushBack(node); if (isStart) { scheduleUpdate(); isStart = false; } }
void AnimationCache::parseVersion2(const ValueMap& animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { std::string name = iter->first; ValueMap& animationDict = const_cast<ValueMap&>(iter->second.asValueMap()); const Value& loops = animationDict["loops"]; bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].asBool(); ValueVector& frameArray = animationDict["frames"].asValueVector(); if ( frameArray.empty() ) { CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name.c_str()); continue; } // Array of AnimationFrames Vector<AnimationFrame*> array(static_cast<int>(frameArray.size())); for (auto& obj : frameArray) { ValueMap& entry = obj.asValueMap(); std::string spriteFrameName = entry["spriteframe"].asString(); SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName); if( ! spriteFrame ) { CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", name.c_str(), spriteFrameName.c_str()); continue; } float delayUnits = entry["delayUnits"].asFloat(); Value& userInfo = entry["notification"]; AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.getType() == Value::Type::MAP ? userInfo.asValueMap() : ValueMapNull); array.pushBack(animFrame); } float delayPerUnit = animationDict["delayPerUnit"].asFloat(); Animation *animation = Animation::create(array, delayPerUnit, loops.getType() != Value::Type::NONE ? loops.asInt() : 1); animation->setRestoreOriginalFrame(restoreOriginalFrame); AnimationCache::getInstance()->addAnimation(animation, name); } }
void AnimationCache::parseVersion1(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::sharedSpriteFrameCache(); DictElement* pElement = NULL; CCDICT_FOREACH(animations, pElement) { Dictionary* animationDict = (Dictionary*)pElement->getObject(); Array* frameNames = (Array*)animationDict->objectForKey("frames"); float delay = animationDict->valueForKey("delay")->floatValue(); Animation* animation = NULL; if ( frameNames == NULL ) { CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", pElement->getStrKey()); continue; } Array* frames = Array::createWithCapacity(frameNames->count()); frames->retain(); Object* pObj = NULL; CCARRAY_FOREACH(frameNames, pObj) { const char* frameName = ((String*)pObj)->getCString(); SpriteFrame* spriteFrame = frameCache->spriteFrameByName(frameName); if ( ! spriteFrame ) { CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", pElement->getStrKey(), frameName); continue; } AnimationFrame* animFrame = new AnimationFrame(); animFrame->initWithSpriteFrame(spriteFrame, 1, NULL); frames->addObject(animFrame); animFrame->release(); } if ( frames->count() == 0 ) { CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", pElement->getStrKey()); continue; } else if ( frames->count() != frameNames->count() ) { CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", pElement->getStrKey()); } animation = Animation::create(frames, delay, 1); AnimationCache::sharedAnimationCache()->addAnimation(animation, pElement->getStrKey()); frames->release(); }
void AnimationCache::parseVersion1(const ValueMap& animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { const ValueMap& animationDict = iter->second.asValueMap(); const ValueVector& frameNames = animationDict.at("frames").asValueVector(); float delay = animationDict.at("delay").asFloat(); Animation* animation = nullptr; if ( frameNames.empty() ) { CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", iter->first.c_str()); continue; } ssize_t frameNameSize = frameNames.size(); Vector<AnimationFrame*> frames(frameNameSize); for (auto& frameName : frameNames) { SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName.asString()); if ( ! spriteFrame ) { CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", iter->first.c_str(), frameName.asString().c_str()); continue; } AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, 1, ValueMap()); frames.pushBack(animFrame); } if ( frames.empty() ) { CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str()); continue; } else if ( frames.size() != frameNameSize ) { CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str()); } animation = Animation::create(frames, delay, 1); AnimationCache::getInstance()->addAnimation(animation, iter->first.c_str()); } }
void Sprite::setSpriteFrame(const std::string &spriteFrameName) { CCASSERT(!spriteFrameName.empty(), "Sprite::setSpriteFrame-->spriteFrameName should not be empty!"); if (spriteFrameName.empty()) { return; } SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName); CCASSERT(spriteFrame, std::string("Invalid spriteFrameName :").append(spriteFrameName).c_str()); setSpriteFrame(spriteFrame); }
KDvoid SampleLayer::initItem ( KDvoid ) { SpriteFrameCache* pFrameCache = SpriteFrameCache::getInstance ( ); pFrameCache->addSpriteFramesWithFile ( "playing_jelly.plist" ); m_pJellyDictionary = (Dictionary*) Dictionary::createWithContentsOfFile ( "playing_jelly.plist" )->objectForKey ( "frames" ); m_pJellyDictionary->retain ( ); m_pItemArray = Array::create ( ); m_pItemArray->retain ( ); m_pTempArray = Array::create ( ); m_pTempArray->retain ( ); m_nItemCount = 0; }
KDvoid SampleLayer::addBackground ( KDvoid ) { SpriteFrameCache* pFrameCache = SpriteFrameCache::getInstance ( ); pFrameCache->addSpriteFramesWithFile ( "tm01_bg.plist" ); Sprite* pSprite1 = Sprite::createWithSpriteFrameName ( "tm01_bg1.png" ); Sprite* pSprite2 = Sprite::createWithSpriteFrameName ( "tm01_bg2.png" ); Sprite* pSprite3 = Sprite::createWithSpriteFrameName ( "tm01_black.png" ); Sprite* pSprite4 = Sprite::create ( "floor.png" ); pSprite1->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite2->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite3->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite4->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite1->getTexture ( )->setAliasTexParameters ( ); pSprite2->getTexture ( )->setAliasTexParameters ( ); pSprite3->getTexture ( )->setAliasTexParameters ( ); pSprite4->getTexture ( )->setAliasTexParameters ( ); Sprite* pSprite1_1 = Sprite::createWithSpriteFrameName ( "tm01_bg1.png" ); Sprite* pSprite2_1 = Sprite::createWithSpriteFrameName ( "tm01_bg2.png" ); Sprite* pSprite3_1 = Sprite::createWithSpriteFrameName ( "tm01_black.png" ); Sprite* pSprite4_1 = Sprite::create ( "floor.png" ); pSprite1_1->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite2_1->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite3_1->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite4_1->setAnchorPoint ( Point ( 0.0f, 0.0f ) ); pSprite1_1->getTexture ( )->setAliasTexParameters ( ); pSprite2_1->getTexture ( )->setAliasTexParameters ( ); pSprite3_1->getTexture ( )->setAliasTexParameters ( ); pSprite4_1->getTexture ( )->setAliasTexParameters ( ); ParallaxScrollNode* pParallaxNode = ParallaxScrollNode::create ( ); pParallaxNode->addInfiniteScrollXWithZ ( 0, Point ( 0.5f, 0.0f ), Point ( 0, 0 ), pSprite1, pSprite1_1, KD_NULL ); pParallaxNode->addInfiniteScrollXWithZ ( 1, Point ( 0.7f, 0.0f ), Point ( 0, 0 ), pSprite2, pSprite2_1, KD_NULL ); pParallaxNode->addInfiniteScrollXWithZ ( 2, Point ( 1.0f, 0.0f ), Point ( 0, 0 ), pSprite4, pSprite4_1, KD_NULL ); //pParallaxNode->addInfiniteScrollXWithZ ( 2, Point ( 1.0f, 0.0f ), Point ( 0, 0 ), pSprite3, pSprite3_1, KD_NULL ); this->addChild ( pParallaxNode , 0, 100 ); this->schedule ( schedule_selector ( SampleLayer::moveBackground ) ); }
// on "init" you need to initialize your instance bool InteractiveLayerV1::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); SpriteFrameCache* sfCache = SpriteFrameCache::getInstance(); sfCache->addSpriteFramesWithFile("btn_lp.plist"); sfCache->addSpriteFramesWithFile("btn_rp.plist"); //使用第一帧精灵初始化对象,精灵对象的名字与plist中的名字一致 this->_uiLPBeginFlag = Sprite::createWithSpriteFrameName("btn_lp_00.png"); this->_uiLPBeginFlag->setPosition(Vec2(origin.x + this->LPBeginFlagPosition, origin.y + 140)); this->addChild(this->_uiLPBeginFlag, 0); // add right began flag this->_uiRPBeginFlag = Sprite::createWithSpriteFrameName("btn_rp_00.png"); this->_uiRPBeginFlag->setPosition(Vec2(origin.y + this->RPBeginFlagPosition, origin.y + 140)); this->addChild(this->_uiRPBeginFlag, 0); /* auto testFlag = Sprite::create("CloseNormal.png"); testFlag->setName("testFlag"); // position the sprite on the center of the screen testFlag->setPosition(Vec2(0,100)); this->addChild(testFlag, 0); */ //register touch event(touch all) auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); auto listenerTA = EventListenerTouchAllAtOnce::create(); listenerTA->onTouchesBegan = CC_CALLBACK_2(InteractiveLayerV1::onTouchsBegan, this); listenerTA->onTouchesEnded = CC_CALLBACK_2(InteractiveLayerV1::onTouchsEnded, this); listenerTA->onTouchesCancelled = CC_CALLBACK_2(InteractiveLayerV1::onTouchsCancelled, this); dispatcher->addEventListenerWithSceneGraphPriority(listenerTA, this); return true; }
void ProgressBars::createBars(cocos2d::Layer *layerToSpawn) { SpriteFrameCache* cache = SpriteFrameCache::getInstance(); spriteBatch = SpriteBatchNode::create("Atlases/ui.png"); cache->addSpriteFramesWithFile("Atlases/ui.plist"); visibleSize = Director::getInstance()->getVisibleSize(); originalBarHeight = 172; sideOffset = 26; topOffset = 10; //Bottom food (static) Sprite *foodProgressBottom = Sprite::createWithSpriteFrameName("foodBottomProgress.png"); foodProgressBottom->setPosition(Vec2(sideOffset, (visibleSize.height/2) - originalBarHeight)); spriteBatch->addChild(foodProgressBottom, 11); //Bottom timer (static) Sprite *timerProgressBottom = Sprite::createWithSpriteFrameName("timerBottomProgress.png"); timerProgressBottom->setPosition(Vec2((visibleSize.width) - sideOffset, (visibleSize.height/2) - originalBarHeight)); spriteBatch->addChild(timerProgressBottom, 11); //Middle of progress food left (move down as progress) foodProgressMiddle = Sprite::createWithSpriteFrameName("foodMiddleProgress.png"); foodProgressMiddle->setPosition(Vec2(sideOffset, (visibleSize.height/2))); spriteBatch->addChild(foodProgressMiddle, 10); //Middle of progress timer (move down as progress) timerProgressMiddle = Sprite::createWithSpriteFrameName("timerMiddleProgress.png"); timerProgressMiddle->setPosition(Vec2((visibleSize.width) - sideOffset, (visibleSize.height/2))); spriteBatch->addChild(timerProgressMiddle, 10); //Top of progress food left (move down as progress) foodProgressTop = Sprite::createWithSpriteFrameName("foodTopProgress.png"); foodProgressTop->setPosition(Vec2(sideOffset, (visibleSize.height/2) + (originalBarHeight+topOffset))); spriteBatch->addChild(foodProgressTop, 12); //Top of progress timer (move down as progress) timerProgressTop = Sprite::createWithSpriteFrameName("timerTopProgress.png"); timerProgressTop->setPosition(Vec2((visibleSize.width) - sideOffset, (visibleSize.height/2) + (originalBarHeight+topOffset))); spriteBatch->addChild(timerProgressTop, 12); layerToSpawn->addChild(spriteBatch); resetFood(); }
void Bacterial::setLevel(int value) { if(level != value && value <= MAXLEVEL) { level = value; SpriteFrameCache* cache = SpriteFrameCache::getInstance(); if(level > 0) { inited = true; SpriteFrame* frame = cache->getSpriteFrameByName(String::createWithFormat("res/%d%d.png", type, level)->getCString()); bg->setSpriteFrame(frame); } else { inited = false; } } }
Size CTextRich::_getMesureSpriteContentSize(const std::string& path) { if (_mesureSprite == nullptr) { _mesureSprite = Sprite::create(); _mesureSprite->retain(); } SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *spriteFrame = cache->getSpriteFrameByName(path); if (spriteFrame) { _mesureSprite->setSpriteFrame(spriteFrame); return _mesureSprite->getContentSize(); }else{ CCLOG("miss SpriteFrame: ",path.c_str()); return Size(); } }
cocos2d::Animation * Entity::createAnimation(const char *str, int num) { //»ñÈ¡»º´æʵÀý SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); SpriteFrame *frame = nullptr; Vector<SpriteFrame*> frameVec; for (int i = 0; i < num; i++) { frame = frameCache->getSpriteFrameByName(StringUtils::format("%s%d.png", str, i)); frameVec.pushBack(frame); } Animation *animation = Animation::createWithSpriteFrames(frameVec); animation->setLoops(-1); animation->setDelayPerUnit(0.2f); return animation; }
Action* CSprite::createFrameCaheAction(const string& pattern, int count, float duration, bool loop) { SpriteFrameCache* spriteFrameCache = SpriteFrameCache::getInstance(); Vector<SpriteFrame*>* framesVector = new Vector<SpriteFrame*>; char frameName[128]; for(int i = 1; i <= count; i++){ sprintf(frameName, pattern.c_str(), i); SpriteFrame* frame = spriteFrameCache->getSpriteFrameByName(frameName); framesVector->pushBack(frame); } float delay = duration / framesVector->size(); Animation* animation = Animation::createWithSpriteFrames(*framesVector, delay); Animate* animate = Animate::create(animation); Action* action = NULL; if (loop) { action = RepeatForever::create(animate); } else { action = (Action*) animate; } delete framesVector; return action; }
bool MenuLayer::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto closeItem = MenuItemImage::create("","",CC_CALLBACK_1(MenuLayer::menuCloseCallback, this)); SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *frameNormal = cache->getSpriteFrameByName("CloseNormal.png"); closeItem->setNormalSpriteFrame(frameNormal); SpriteFrame *frameSelected = cache->getSpriteFrameByName("CloseSelected.png"); closeItem->setNormalSpriteFrame(frameSelected); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2, origin.y + closeItem->getContentSize().height / 2)); auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 0); return true; }
bool SpriteAnimation::init(const std::string& plist, float delay) { if (!Sprite::init()) { return false; } _animation = AnimationCache::getInstance()->getAnimation(plist); if (!_animation) { SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(plist); FrameParser parser; Vector<SpriteFrame*> animFrames = parser.getFrames(plist); _animation = Animation::createWithSpriteFrames(animFrames, delay); AnimationCache::getInstance()->addAnimation(_animation, plist); } if (_animation->getFrames().empty()) { return false; } _action = Animate::create(_animation); _action->retain(); _repeatAction = RepeatForever::create(_action); _repeatAction->retain(); //set the current frame to first frame of animation setSpriteFrame(_animation->getFrames().at(0)->getSpriteFrame()); return true; }
RepeatForever* PeerJelly::moving() { // 3. repeat the frame int numFrame = 3; cocos2d::Vector<cocos2d::SpriteFrame *> frames; SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); char file[100] = {0}; for (int i = 0; i < numFrame; i++) { sprintf(file, "redJelly_%d.png", i+1); SpriteFrame *frame = frameCache->getSpriteFrameByName(file); frames.pushBack(frame); } Animation *animation = Animation::createWithSpriteFrames(frames, 0.3f); Animate *animate = Animate::create(animation); auto easeInAnimation = EaseIn::create(animate, 0.3f); RepeatForever *repeat = RepeatForever::create(easeInAnimation); return repeat; }