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; }
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; }
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"); } }
//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 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; }
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 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; }
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; }
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 ) ); }
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(); }
// 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; }
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; }
void Item::explode(){ //play the explode animation explodeIndicator = 1; if(haveExplode == 0){ haveExplode=1; SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("explode/explode.plist"); Vector<SpriteFrame*> animFrames(14); char str[100]={0}; for(int i=1; i<=14; i++){ sprintf(str, "exp%d.png",i); SpriteFrame* frame = cache->getSpriteFrameByName(str); animFrames.insert(i-1, frame); } Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* act = Animate::create(animation); Sequence* endAct=Sequence::create(act,CallFunc::create( std::bind(&Item::explodeEnd,this) ),NULL); item->runAction(endAct); } }
bool Item::initItem(string filename,char frameName[],Name itemName) { log("Create Item"); this->initWithFile(filename); this->setAnchorPoint(Vec2(0.5,0.5)); this->itemName = itemName; SpriteBatchNode* spriteBatch = SpriteBatchNode::create(filename); SpriteFrameCache* cache = SpriteFrameCache::sharedSpriteFrameCache(); cache->addSpriteFramesWithFile("spritesheets/items.plist"); this->createWithSpriteFrameName(filename); this->addChild(spriteBatch); //positionItem(); bounce = this->createAnimAction(frameName, cache); bounce->retain(); this->runAction(bounce); return true; }
Animate* EffectUtil::getSkillEffectById(int id,int loop){ SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile(String::createWithFormat("Skill/Effect/%d.plist",id)->getCString(), String::createWithFormat("Skill/Effect/%d.png",id)->getCString()); SpriteFrame* temp; Vector<SpriteFrame*> v; int index = 1; do{ CCLOG("INDEX = %d",index); temp = cache->getSpriteFrameByName(String::createWithFormat("%d_%d.png",id,index)->getCString()); index++; if(temp == nullptr){ break; }else{ v.pushBack(temp); } }while(true); Animation* animation = Animation::createWithSpriteFrames(v); animation->setLoops(loop); animation->setDelayPerUnit(0.1f); Animate* ret = Animate::create(animation); return ret; }
void gameLevel2::shipExplosions(Vec2 vec,bool scale) { SpriteBatchNode* spritebatch = SpriteBatchNode::create("animations/explosion.png"); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("animations/explosion.plist"); auto explosion = Sprite::createWithSpriteFrameName("explosion_01.png"); explosion->setPosition(vec); if (scale) explosion->setScale(0.5); spritebatch->addChild(explosion); this->addChild(spritebatch); Vector<SpriteFrame*> animFrames(48); char str[100] = { 0 }; for (int i = 1; i < 49; i++) { sprintf(str, "explosion_%02d.png", i); SpriteFrame* frame = cache->getSpriteFrameByName(str); animFrames.pushBack(frame); } Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.02); explosion->runAction(Sequence::create(Animate::create(animation),RemoveSelf::create(),NULL)); }
// on "init" you need to initialize your instance bool BeginCuesLayerV2::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } this->scheduleUpdate(); //this->schedule(schedule_selector(BeginCuesLayerV2::update4Running), 0.2); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); this->initUIHeader(); this->_layerBars = BarsLayer::createLayer(); this->addChild(this->_layerBars, 0); // left player cue message auto ctlLPMessage = Sprite::create("ui/ready_cues.png"); ctlLPMessage->setTag(HUD_UI_LP_READY_CUE); ctlLPMessage->setPosition(Vec2(470, 280)); this->addChild(ctlLPMessage, 0); auto lAct1 = MoveTo::create(0.5, Vec2(470, 270)); auto lAct2 = MoveTo::create(0.5, Vec2(470, 280)); auto lActS = Sequence::create(lAct1, lAct2, NULL); auto lRepeat = CCRepeatForever::create(lActS); lRepeat->setTag(HUD_ACT_LP_READY_CUE); ctlLPMessage->runAction(lRepeat); // left player cue message auto ctlRPMessage = Sprite::create("ui/ready_cues.png"); ctlRPMessage->setTag(HUD_UI_RP_READY_CUE); ctlRPMessage->setPosition(Vec2(867, 280)); this->addChild(ctlRPMessage, 0); auto rAct1 = MoveTo::create(0.5, Vec2(867, 270)); auto rAct2 = MoveTo::create(0.5, Vec2(867, 280)); auto rActS = Sequence::create(rAct1, rAct2, NULL); auto rRepeat = CCRepeatForever::create(rActS); rRepeat->setTag(HUD_ACT_RP_READY_CUE); ctlRPMessage->runAction(rRepeat); SpriteFrameCache* sfCache =SpriteFrameCache::getInstance(); sfCache->addSpriteFramesWithFile("countdown.plist"); //使用第一帧精灵初始化对象,精灵对象的名字与plist中的名字一致 this->_uiCountdown = Sprite::createWithSpriteFrameName("cd3.png"); this->_uiCountdown->setPosition(Vec2(origin.x + visibleSize.width/2 , origin.y + visibleSize.height/2)); this->_uiCountdown->setVisible(false); this->addChild(this->_uiCountdown, 0); sfCache->addSpriteFramesWithFile("player_status.plist"); this->_uiLPStatus = Sprite::createWithSpriteFrameName("player_status_0.png"); this->_uiLPStatus->setPosition(Vec2(origin.x + 300 , origin.y + visibleSize.height - 300)); this->addChild(this->_uiLPStatus, 0); this->_uiRPStatus = Sprite::createWithSpriteFrameName("player_status_0.png"); this->_uiRPStatus->setPosition(Vec2(origin.x + visibleSize.width - 300 , origin.y + visibleSize.height - 300)); this->addChild(this->_uiRPStatus, 0); auto valueMap = cocos2d::FileUtils::getInstance()->getValueMapFromFile("chinese.plist"); std::string strJia = valueMap["come"].asString(); std::string strYou = valueMap["on"].asString(); auto uiTime1 = Label::createWithTTF(strJia, "fonts/msyh.ttf", 40); uiTime1->setPosition(Vec2(origin.x + visibleSize.width / 2 - 36, origin.y + visibleSize.height - 107)); this->addChild(uiTime1, 0); auto uiTime2 = Label::createWithTTF(strYou, "fonts/msyh.ttf", 40); uiTime2->setPosition(Vec2(origin.x + visibleSize.width / 2 + 36, origin.y + visibleSize.height - 107)); this->addChild(uiTime2, 0); return true; }
void Character::createCharacter(cocos2d::Layer *layerToSpawn, FoodSpawner &foodSpawner) { SpriteFrameCache* cache = SpriteFrameCache::getInstance(); characterBatch = SpriteBatchNode::create("Atlases/characters.png"); cache->addSpriteFramesWithFile("Atlases/characters.plist"); bodyID.push_back(3); hairID.push_back(2); eyeID.push_back(1); mouthID.push_back(0); currentCharacterID = 0; //BodyID std::ostringstream bodyIDStr; bodyIDStr << bodyID.at(currentCharacterID); //EyeID std::ostringstream eyeIDStr; eyeIDStr << eyeID.at(currentCharacterID); //HairID std::ostringstream hairIDStr; hairIDStr << hairID.at(currentCharacterID); //MouthID std::ostringstream mouthIDStr; mouthIDStr << mouthID.at(currentCharacterID); body = Sprite::createWithSpriteFrameName("body" + bodyIDStr.str() + ".png"); body->setPosition(Vec2(0, 0)); characterBatch->addChild(body, 10); eyes = Sprite::createWithSpriteFrameName("eyes" + eyeIDStr.str() + ".png"); eyes->setPosition(Vec2(0, 64)); characterBatch->addChild(eyes, 11); hair = Sprite::createWithSpriteFrameName("haircut" + hairIDStr.str() + "_0.png"); hair->setPosition(Vec2(0, 96)); hair->setScale(1.06f); characterBatch->addChild(hair, 14); mouth = Sprite::createWithSpriteFrameName("mouth" + mouthIDStr.str() + "_open.png"); mouth->setPosition(Vec2(0, 54)); characterBatch->addChild(mouth, 13); armLeg = Sprite::createWithSpriteFrameName("armLegDown.png"); armLeg->setPosition(Vec2(0, 0)); characterBatch->addChild(armLeg, 11); Size visibleSize = Director::getInstance()->getVisibleSize(); characterBatch->setPosition(visibleSize.width/2, (body->getSpriteFrame()->getOriginalSizeInPixels().height / 4)); characterBatch->setScale(2); layerToSpawn->addChild(characterBatch); isBouncingUp = false; currentTime = 0; characterStates = CharacterStates::IDLE; updateHair(); //Lerp length for jumping/idling idleLenght = 0.4f; flyLength = 0.35f; //Idle points that it lerps between idle0Pos = Vec2(visibleSize.width/2, 0); idle1Pos = Vec2(visibleSize.width/2, -64); //Set eatpoint eatPoint = Vec2(visibleSize.width/2, visibleSize.height - (foodSpawner.offsetFromCenter/2)); }
bool HWorld::init() { if (!Layer::init() ) { return false; } sh=this; SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("button.plist","button.png"); //播放游戏中的音乐 SimpleAudioEngine::getInstance()->playBackgroundMusic("gameMusic.mp3",true); //地图 HMap * map = HMap::createMap("img_bg_level_1.jpg"); addChild(map); //主角 HPlayer * player=HPlayer::createPlayer("hero.png"); addChild(player,1,tag_player); bulletBatchNode = SpriteBatchNode::create("heroBullet.png"); this->addChild(bulletBatchNode); //创建子弹逻辑(创建间隔0.4秒) this->schedule(schedule_selector(HWorld::autoCreateBullet),0.4f); //创建敌怪逻辑 this->schedule(schedule_selector(HWorld::autoCreateEnemy)); if(touchType) { //this->setTouchEnabled(true); }else { //虚拟手柄 Button * button = Button::createButton(player, this); addChild(button); } MenuItemImage *pause = MenuItemImage::create("pause.png", "pause.png", CC_CALLBACK_1(HWorld::doPause, this)); pause->setAnchorPoint(Vec2(1, 1)); pause->setPosition(Vec2(Director::getInstance()->getWinSize().width-10, Director::getInstance()->getWinSize().height-10)); Menu *menu = Menu::create(pause, NULL); menu->setAnchorPoint(Vec2(0, 0)); addChild(menu, 1, 10); menu->setPosition(Vec2(0, 0)); smallEnemyTime = 0; mediumEnemyTime = 0; bigEnemyTime = 0; smallEnemyTime2 = 0; mediumEnemyTime2 = 0; auto _listener_touch = EventListenerTouchOneByOne::create(); _listener_touch->onTouchBegan = CC_CALLBACK_2(HWorld::TouchBegan, this); _listener_touch->onTouchMoved = CC_CALLBACK_2(HWorld::TouchMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_listener_touch, this); return true; }
void ChapterScene::createLayersContent() { GameModel* gameModel = GameModel::getInstance(); Size displayResolutionSize = gameModel->getDisplayResolutionSize(); Face* backgroundFace = new Face(); backgroundFace->initWithFile(ANI_BACKGROUND); backgroundFace->setScale(CONF_FAKE_1); backgroundFace->setPosition(displayResolutionSize.width / 2, displayResolutionSize.height / 2); this->backgroundLayer->addChild(backgroundFace); Face* chapterTitle = new Face(); chapterTitle->initWithSpriteFrameName(ANI_CHAPTER_TITLE); chapterTitle->setPosition(displayResolutionSize.width / 2, displayResolutionSize.height - chapterTitle->getContentSize().height / 2 - 20); this->mainLayer->addChild(chapterTitle); UGMenu* mainMenu = UGMenu::create(); mainMenu->setPosition(Point::ZERO); this->mainLayer->addChild(mainMenu); MenuItemSprite* backButton = Utils::createButton((char*) TXT_BACK, 16, ANI_BUTTON, ANI_BUTTON); backButton->setCallback(CC_CALLBACK_1(ChapterScene::backButtonClick, this)); backButton->setPosition(gameModel->getDisplayResolutionSize().width / 2, 20 + backButton->getContentSize().height / 2); mainMenu->addChild(backButton); this->nodes->setObject(backButton, NODE_BUTTON_BACK); // create chapters this->chapterLayer = UGLayerColor::create(); float totalChapterSize = gameModel->getMapData()->getLevelSize(); float distancePerChapter = CONF_DISTANCE_PER_CHAPTER; float totalChapterWidth = (totalChapterSize - 1) * distancePerChapter; Face* chapterTemp = new Face(); chapterTemp->initWithSpriteFrameName(ANI_BOX_CHAPTER); this->chapterTempSize = chapterTemp->getContentSize(); this->chapterLayer->setContentSize(Size(totalChapterWidth + this->chapterTempSize.width, displayResolutionSize.height / 2)); this->chapterLayer->setPosition(displayResolutionSize.width / 2 - this->chapterTempSize.width / 2, displayResolutionSize.height / 2 - this->chapterLayer->getContentSize().height / 2); this->chapterLayerOffset = this->chapterLayer->getPosition(); this->mainLayer->addChild(this->chapterLayer); float posX = this->chapterTempSize.width / 2; float posY = this->chapterLayer->getContentSize().height / 2; for (int i = 0; i < totalChapterSize; i++) { Face* levelBox = new Face(); if (!gameModel->checkLevelLock(i + 1)) { levelBox->initWithSpriteFrameName(ANI_BOX_CHAPTER); levelBox->setTag(i + 1); { int chapter = gameModel->getMapData()->getChapter(i + 1); int chapterLevel = gameModel->getMapData()->getChapterLevel(i + 1); char mapPath[200]; sprintf(mapPath, DOC_BG_MAP, chapter, chapterLevel); SpriteFrameCache* sfc = SpriteFrameCache::getInstance(); sfc->addSpriteFramesWithFile(mapPath); char bg1Path[200]; sprintf(bg1Path, ANI_MAP, chapter, chapterLevel, 1); Face* chapterThumb = new Face(); chapterThumb->initWithSpriteFrameName(bg1Path); chapterThumb->setPosition(levelBox->getContentSize().width / 2, levelBox->getContentSize().height / 2 - 10); chapterThumb->setTextureRect(Rect(0, 0, 160, 115)); levelBox->addChild(chapterThumb); string levelName = gameModel->getMapData()->getLevelName(i + 1); char levelNameChar[200]; sprintf(levelNameChar, "%s", levelName.data()); Label* levelNameLabel = Label::createWithBMFont(FONT_GAME_SMALL, levelNameChar); levelNameLabel->setPosition(chapterThumb->getPosition() + Point(0, chapterThumb->getContentSize().height / 2 + 12)); levelBox->addChild(levelNameLabel); } } else { levelBox->setTag(-1); levelBox->initWithSpriteFrameName(ANI_BOX_CHAPTER_LOCK); } levelBox->setPosition(posX, posY); posX = posX + distancePerChapter; this->chapterLayer->addChild(levelBox); } // add parent button for share layer this->shareLayer->getParentButtons()->pushBack((MenuItemSprite*) this->nodes->objectForKey(NODE_BUTTON_BACK)); }
// on "init" you need to initialize your instance bool gameLevel2::init() { if ( !Layer::init() ) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); origin = Director::getInstance()->getVisibleOrigin(); soundState = UserDefault::getInstance()->sharedUserDefault()->getBoolForKey("sound",true); if(soundState)CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("Sounds/backgroundMusic.mp3",true); shipHealt = enemyCount = 3; score = 0; isEnemyReady = false; isShipAlive = true; #pragma region PRELOAD EXPLOSION SpriteBatchNode* spritebatch = SpriteBatchNode::create("animations/explosion.png"); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("animations/explosion.plist"); #pragma endregion #pragma region Ship Sprite Creation ship = Sprite::create("ship.png"); auto shipPhysics = PhysicsBody::createBox(ship->getContentSize(), PhysicsMaterial(0.1, 1.0, 0)); shipPhysics->setDynamic(true); ship->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y -50)); if (visibleSize.width < visibleSize.height) ship->setScale(1.2); shipPhysics->setCategoryBitmask(0x01); shipPhysics->setCollisionBitmask(0); shipPhysics->setContactTestBitmask(0x08); ship->setPhysicsBody(shipPhysics); this->addChild(ship, 2); auto shipMove = MoveTo::create(1, Vec3(ship->getPositionX(), origin.y + visibleSize.height / 4, ship->getPositionZ())); auto shipEase = EaseOut::create(shipMove, 1); ship->runAction(shipEase); #pragma endregion #pragma region Heart and ShipHealt Label Creation healtLbl = Label::createWithTTF("3", "fonts/divisibleinvisible.ttf", 24); healtLbl->setPosition(Vec2(origin.x + visibleSize.width - 20, origin.y + visibleSize.height - 40)); this->addChild(healtLbl, 2); auto heart = Sprite::create("heart.png"); heart->setScale(0.7); heart->setPosition(Vec2(healtLbl->getPositionX() - 10 - heart->getContentSize().width / 2, origin.y + visibleSize.height - 40)); this->addChild(heart, 2); if (soundState)CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("Sounds/shipexit.mp3"); #pragma endregion #pragma region Enemy Count Label Creation enemyCountLbl = Label::createWithTTF("3", "fonts/divisibleinvisible.ttf", 24); enemyCountLbl->setPosition(Vec2(heart->getPositionX() - 10 - heart->getContentSize().width, origin.y + visibleSize.height - 40)); this->addChild(enemyCountLbl, 2); auto enemySymbol = Sprite::create("enemysymbol.png"); enemySymbol->setPosition(Vec2(enemyCountLbl->getPositionX() - 20 - enemySymbol->getContentSize().width / 2, origin.y + visibleSize.height - 40)); this->addChild(enemySymbol, 2); #pragma endregion #pragma region Score icon and Label Creation scoreIcon = Sprite::create("score.png"); scoreIcon->setPosition(Vec2(origin.x + 10 + scoreIcon->getContentSize().width / 2, origin.y + visibleSize.height - 40)); this->addChild(scoreIcon, 2); scoreLbl = Label::createWithTTF("0", "fonts/divisibleinvisible.ttf", 24); scoreLbl->setPosition(Vec2(scoreIcon->getPositionX() + scoreLbl->getContentSize().width + 20, origin.y + visibleSize.height - 40)); this->addChild(scoreLbl, 2); #pragma endregion #pragma region TouchEvents auto lis = EventListenerTouchOneByOne::create(); lis->onTouchBegan = [=](Touch *t, Event *e) { return true; }; lis->onTouchMoved = [=](Touch *t, Event *e) { }; lis->onTouchEnded = [=](Touch *t, Event *e) { gameLevel2::fireTheFuckinBullet(); }; auto dispatcher = this->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(lis, this); #pragma endregion #pragma region Contact defining auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(gameLevel2::onContactBegins,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener,this); #pragma endregion #pragma region Create first enemy and schedulers gameLevel2::createFirstEnemy(); schedule(schedule_selector(gameLevel2::addStars), 1); auto accel = EventListenerAcceleration::create(CC_CALLBACK_2(gameLevel2::onAcceleration,this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accel,this); Device::setAccelerometerEnabled(true); #pragma endregion return true; }
bool CommonTextureManager::init() { SpriteFrameCache* spriteFrameCache = SpriteFrameCache::getInstance(); spriteFrameCache->addSpriteFramesWithFile("common.plist"); return true; }
// 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(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //add image texture to cache SpriteFrameCache* frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("WormHeroSaga.plist"); //create background auto background = Sprite::createWithSpriteFrameName("Background.png"); background->setPosition(visibleSize/2); this->addChild(background); moon = Sprite::createWithSpriteFrameName("MoonLaugh.png"); moon->setPosition(Director::getInstance()->convertToGL(Vec2(490,234))); this->addChild(moon); //Start button Sprite* startButtonItem_normal = Sprite::createWithSpriteFrameName("StartButton_normal.png"); Sprite* startButtonItem_onClick = Sprite::createWithSpriteFrameName("StartButton_onClick.png"); MenuItemSprite* startButton = MenuItemSprite::create(startButtonItem_normal, startButtonItem_onClick, CC_CALLBACK_1(HelloWorld::startButtonCallBack, this)); startButton->setPosition(Director::getInstance()->convertToGL(Vec2(visibleSize.width/2,730))); startMenu = Menu::create(startButton, NULL); startMenu->setPosition(Vec2::ZERO); startMenu->setTag(START_TAG); this->addChild(startMenu); //add stop button with setting menus Sprite* stopButton = Sprite::createWithSpriteFrameName("StopButton.png"); MenuItemSprite* stopButtonItem = MenuItemSprite::create(stopButton, stopButton, CC_CALLBACK_1(HelloWorld::stopButtonCallBack, this)); stopButtonItem->setPosition(Director::getInstance()->convertToGL(Vec2(71,38))); stopMenu = Menu::create(stopButtonItem, NULL); stopMenu->setPosition(Vec2::ZERO); stopMenu->setTag(STOP_TAG); stopMenu->setVisible(false); this->addChild(stopMenu); //below list set menu //music setting in setting menu Sprite* musicOn = Sprite::createWithSpriteFrameName("MusicOn.png"); Sprite* musicOff = Sprite::createWithSpriteFrameName("MusicOff.png"); auto musicOnSprite = MenuItemSprite::create(musicOn,musicOn); auto musicOffSprite = MenuItemSprite::create(musicOff,musicOff); auto musicToggleMenuItem = MenuItemToggle::createWithCallback(CC_CALLBACK_1(HelloWorld::MusicOnCallBack, this), musicOnSprite, musicOffSprite, NULL); musicToggleMenuItem->setPosition(Director::getInstance()->convertToGL(Vec2(visibleSize.width/2-10, 550))); //effect setting in setting menu Sprite* effectOn = Sprite::createWithSpriteFrameName("EffectOn.png"); Sprite* effectOff = Sprite::createWithSpriteFrameName("EffectOff.png"); auto effectOnSprite = MenuItemSprite::create(effectOn,effectOn); auto effectOffSprite = MenuItemSprite::create(effectOff,effectOff); auto effectToggleMenuItem = MenuItemToggle::createWithCallback(CC_CALLBACK_1(HelloWorld::MusicOnCallBack, this), effectOnSprite, effectOffSprite, NULL); effectToggleMenuItem->setPosition(Director::getInstance()->convertToGL(Vec2(visibleSize.width/2, 730))); //play setting in setting menu Sprite* PlayButton = Sprite::createWithSpriteFrameName("PlayButton.png"); MenuItemSprite* PlayButtonItem = MenuItemSprite::create(PlayButton, PlayButton, CC_CALLBACK_1(HelloWorld::playCallBack, this)); PlayButtonItem->setPosition(Director::getInstance()->convertToGL(Vec2(visibleSize.width/2, 910))); //add all items into setMenu setMenu = Menu::create(musicToggleMenuItem, effectToggleMenuItem, PlayButtonItem, NULL); setMenu->setPosition(Vec2::ZERO); this->addChild(setMenu); setMenu->setVisible(false); return true; }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } this->isGameOver = false; visibleSize = Director::getInstance()->getVisibleSize(); // Ground setup groundSprite0 = Sprite::create("ground.png"); this->addChild(groundSprite0); groundSprite0->setPosition(Vec2(groundSprite0->getContentSize().width/2.0 , groundSprite0->getContentSize().height/2)); groundSprite1 = Sprite::create("ground.png"); this->addChild(groundSprite1); groundSprite1->setPosition(Vec2(visibleSize.width + groundSprite1->getContentSize().width/2.0 -10, groundSprite1->getContentSize().height/2)); auto groundbody0 = PhysicsBody::createBox(groundSprite0->getContentSize()); groundbody0->setDynamic(false); groundbody0->setContactTestBitmask(true); groundSprite0->setPhysicsBody(groundbody0); auto groundbody1 = PhysicsBody::createBox(groundSprite1->getContentSize()); groundbody1->setDynamic(false); groundbody1->setContactTestBitmask(true); groundSprite1->setPhysicsBody(groundbody1); // SkyGround setup Sprite *skySprite0 = Sprite::create("flappy_background.png"); Sprite *skySprite1 = Sprite::create("flappy_background.png"); Sprite *skySprite2 = Sprite::create("flappy_background.png"); this->addChild(skySprite0); this->addChild(skySprite1); this->addChild(skySprite2); skySprite0->setPosition(visibleSize.width/2, 168 + 200); skySprite1->setPosition(visibleSize.width/2 - skySprite1->getContentSize().width, 168 + 200); skySprite2->setPosition(visibleSize.width/2 + skySprite1->getContentSize().width, 168 + 200); // bird setup /* Sprite *birdSprite = Sprite::create("flappybird1.png"); this->addChild(birdSprite); birdSprite->setPosition(visibleSize.width/2, visibleSize.height/2 + 120); */ SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("bird.plist"); auto flyAnim = Animation::create(); for (int i = 1; i < 4; i++) { SpriteFrame * frame = cache->getSpriteFrameByName("flappybird" + to_string(i) + ".png"); flyAnim->addSpriteFrame(frame); } auto birdSprite = Sprite::createWithSpriteFrameName("flappybird1.png"); flyAnim->setDelayPerUnit(0.2f); auto action = Animate::create(flyAnim); auto animation = RepeatForever::create(action); birdSprite->runAction(animation); birdSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2 + 80)); this->addChild(birdSprite); auto birdBody = PhysicsBody::createCircle(17.0); birdBody->setDynamic(true); birdBody->setMass(1.0f); birdBody->setVelocity(Vec2(4.0f, 2.0f)); birdBody->setVelocityLimit(50); birdBody->setContactTestBitmask(true); birdSprite->setPhysicsBody(birdBody); //pipe setup topPipeSprite = Sprite::create("top_pipe.png"); bottomPipeSprite = Sprite::create("bottom_pipe.png"); topPipeSprite->setPosition(visibleSize.width + topPipeSprite->getContentSize().width/2, 600); auto pipebody0 = PhysicsBody::createBox(topPipeSprite->getContentSize()); pipebody0->setDynamic(false); topPipeSprite->setPhysicsBody(pipebody0); pipebody0->setContactTestBitmask(true); auto pipebody1 = PhysicsBody::createBox(bottomPipeSprite->getContentSize()); pipebody1->setDynamic(false); pipebody1->setContactTestBitmask(true); bottomPipeSprite->setPhysicsBody(pipebody1); this->positionBottomPipe(); this->addChild(topPipeSprite); this->addChild(bottomPipeSprite); //setup touch listener auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [=](Touch *touch, Event *event){ if (!this->isGameOver) { birdBody->applyImpulse(Vec2(0, 90.0f)); } log("touch detected!"); return true; }; //setup collision listener auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = [=](PhysicsContact &contact){ log("collision detected!"); auto gameOverSprite = Sprite::create("game_over.png"); gameOverSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); this->addChild(gameOverSprite); this->isGameOver = true; auto restartListner = EventListenerTouchOneByOne::create(); restartListner->setSwallowTouches(true); restartListner->onTouchBegan = [](Touch *touch, Event* event){ Director::getInstance()->replaceScene(HelloWorld::createScene()); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(restartListner, gameOverSprite); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); this->scheduleUpdate(); return true; }
/*virtual*/ bool LeaderScene::init() { if (!Layer::init()) { return false; } // 全层加载 leader_global_size = Director::getInstance()->getVisibleSize(); SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("buttonicon.plist", "buttonicon.png"); // 背景音乐加载 CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("bgmusic.mp3"); // 设置背景 Sprite* bg = Sprite::create("background_iphone5.png"); bg->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height/2)); bg->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(bg); // 从服务端获取到最新排名 Self_Define::Leader_Data get_leader_instance; HttpRequest* request = new HttpRequest(); std::string send_url = "http://118.194.49.4:51999/UploadCommitSearch"; std::string postData = get_leader_instance.get_leader_all(); request->setUrl(send_url.c_str()); request->setRequestType(HttpRequest::Type::POST); request->setRequestData(postData.c_str(),strlen(postData.c_str())); request->setTag("PostUserGetScoreList"); // 发送方式 request->setResponseCallback(this, httpresponse_selector(LeaderScene::onLeaderResponse)); HttpClient::getInstance()->send(request); request->release(); // 列表实现 Sprite* label_First = Sprite::create("labelbg_blue.png"); First_Name = Label::createWithSystemFont("暂无排名数据", "Courier", 25); label_First->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.6)); First_Name->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.6)); label_First->setAnchorPoint(Vec2(0.5, 0.5)); First_Name->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(label_First); this->addChild(First_Name); Sprite* label_Second = Sprite::create("labelbg_blue.png"); Second_Name = Label::createWithSystemFont("暂无排名数据", "Courier", 25); label_Second->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.5)); Second_Name->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.5)); label_Second->setAnchorPoint(Vec2(0.5, 0.5)); Second_Name->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(label_Second); this->addChild(Second_Name); Sprite* label_Third = Sprite::create("labelbg_blue.png"); Third_Name = Label::createWithSystemFont("暂无排名数据", "Courier", 25); label_Third->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.4)); Third_Name->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.4)); label_Third->setAnchorPoint(Vec2(0.5, 0.5)); Third_Name->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(label_Third); this->addChild(Third_Name); Sprite* label_Forth = Sprite::create("labelbg_blue.png"); Forth_Name = Label::createWithSystemFont("暂无排名数据", "Courier", 25); label_Forth->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.3)); Forth_Name->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.3)); label_Forth->setAnchorPoint(Vec2(0.5, 0.5)); Forth_Name->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(label_Forth); this->addChild(Forth_Name); Sprite* label_Fifth = Sprite::create("labelbg_blue.png"); Fifth_Name = Label::createWithSystemFont("暂无排名数据", "Courier", 25); label_Fifth->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.2)); Fifth_Name->setPosition(Vec2(leader_global_size.width/2, leader_global_size.height*0.2)); label_Fifth->setAnchorPoint(Vec2(0.5, 0.5)); Fifth_Name->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(label_Fifth); this->addChild(Fifth_Name); // 历史最高分实现 pointboard = Label::createWithSystemFont("历史最高分: 0", "Courier", 40); pointboard->setPosition(leader_global_size.width/2, leader_global_size.height*0.8); pointboard->setAnchorPoint(Vec2(0.5,0.5)); pointboard->setTextColor(Color4B(70, 70, 70, 80)); this->addChild(pointboard); // 历史最高分排名 pointqueue = Label::createWithSystemFont("历史最高排名: 0", "Courier", 40); pointqueue->setPosition(leader_global_size.width/2, leader_global_size.height*0.75); pointqueue->setAnchorPoint(Vec2(0.5,0.5)); pointqueue->setTextColor(Color4B(70, 70, 70, 80)); this->addChild(pointqueue); // 返回首页按键 p_left = Sprite::createWithSpriteFrameName("left.png"); p_left->setPosition(80, leader_global_size.height-80); p_left->setAnchorPoint(Vec2(0.5, 0.5)); this->addChild(p_left); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(LeaderScene::onTouchBegan, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, p_left); return true; }
bool CGameLevel::init() { LayerBack::init(); g_iGameLevel = 1; size = winSize; // 选关列表 SpriteFrameCache *pCache = SpriteFrameCache::sharedSpriteFrameCache(); pCache->addSpriteFramesWithFile("Image/GameLevel.plist"); // 选关背景 SpriteFrame* pBG = pCache->spriteFrameByName("GameLevelBG.png"); Sprite* pSprite = CCSprite::createWithSpriteFrame(pBG); pSprite->setPosition(ccp(size.width/2, size.height/2)); pSprite->setScale(2.0f); pSprite->setRotation(90.0f); this->addChild(pSprite, 0); _pSprite = pSprite; /**背景特效 */ ParticleSystemQuad *emitter = ParticleSystemQuad::create("Image/Phoenix.plist"); emitter->setPosition(ccp(size.width/2, size.height/2)); this->addChild(emitter, 1); /** 关卡一按钮 */ MenuItemImage *pLevelOne = MenuItemImage::create(); pLevelOne->setTarget(this, menu_selector(CGameLevel::setLevelMode)); pLevelOne->setNormalSpriteFrame(pCache->spriteFrameByName("StartLevel1Normal.png")); pLevelOne->setSelectedSpriteFrame(pCache->spriteFrameByName("StartLevel1Selected.png")); pLevelOne->setPosition(ccp(size.width*0.14f, size.height/2)); pLevelOne->_ID = LEVEL_ONE; /** 关卡二按钮 */ MenuItemImage *pLevelTwo = MenuItemImage::create(); pLevelTwo->setTarget(this, menu_selector(CGameLevel::setLevelMode)); pLevelTwo->setNormalSpriteFrame(pCache->spriteFrameByName("StartLevel2Normal.png")); pLevelTwo->setSelectedSpriteFrame(pCache->spriteFrameByName("StartLevel2Selected.png")); pLevelTwo->setPosition(ccp(size.width/2, size.height*0.8f)); pLevelTwo->_ID = LEVEL_TWO; /** 关卡三按钮 */ MenuItemImage *pLevelThree = MenuItemImage::create(); pLevelThree->setTarget(this, menu_selector(CGameLevel::setLevelMode)); pLevelThree->setNormalSpriteFrame(pCache->spriteFrameByName("StartLevel3Normal.png")); pLevelThree->setSelectedSpriteFrame(pCache->spriteFrameByName("StartLevel3Selected.png")); pLevelThree->setPosition(ccp(size.width*0.86f, size.height/2)); pLevelThree->_ID = LEVEL_THREE; /** 游戏开始按钮 */ MenuItemImage *pStart = MenuItemImage::create(); pStart->setTarget(this, menu_selector(CGameLevel::setLevelStart)); pStart->setNormalSpriteFrame(pCache->spriteFrameByName("GameStartNormal.png")); pStart->setSelectedSpriteFrame(pCache->spriteFrameByName("GameStartSelected.png")); pStart->setPosition(ccp(size.width/2, size.height*0.2f)); /** 菜单 */ _menu->addChild(pLevelOne); _menu->addChild(pLevelTwo); _menu->addChild(pLevelThree); _menu->addChild(pStart); _menu->setPosition(ccp(0, 0)); _menu->setZOrder(3); /** 选中特效 */ m_pSun = ParticleSun::create(); pSprite->addChild(m_pSun, 1); m_pSun->setTexture(TextureCache::sharedTextureCache()->addImage("Image/Fire.png") ); m_pSun->setPosition(_pSprite->convertToNodeSpace(ccp(size.width*0.14f, size.height / 2))); m_pSun->setStartSize(30); _menuItem->setTarget(this, menu_selector(CGameLevel::back)); //_menuItem死活不出现 return true; }
CCBKeyframe* CCBReader::readKeyframe(PropertyType type) { CCBKeyframe *keyframe = new (std::nothrow) CCBKeyframe(); keyframe->autorelease(); keyframe->setTime(readFloat()); CCBKeyframe::EasingType easingType = static_cast<CCBKeyframe::EasingType>(readInt(false)); float easingOpt = 0; Value value; if (easingType == CCBKeyframe::EasingType::CUBIC_IN || easingType == CCBKeyframe::EasingType::CUBIC_OUT || easingType == CCBKeyframe::EasingType::CUBIC_INOUT || easingType == CCBKeyframe::EasingType::ELASTIC_IN || easingType == CCBKeyframe::EasingType::ELASTIC_OUT || easingType == CCBKeyframe::EasingType::ELASTIC_INOUT) { easingOpt = readFloat(); } keyframe->setEasingType(easingType); keyframe->setEasingOpt(easingOpt); if (type == PropertyType::CHECK) { value = readBool(); } else if (type == PropertyType::BYTE) { value = readByte(); } else if (type == PropertyType::COLOR3) { unsigned char r = readByte(); unsigned char g = readByte(); unsigned char b = readByte(); ValueMap colorMap; colorMap["r"] = r; colorMap["g"] = g; colorMap["b"] = b; value = colorMap; } else if (type == PropertyType::DEGREES) { value = readFloat(); } else if (type == PropertyType::SCALE_LOCK || type == PropertyType::POSITION || type == PropertyType::FLOAT_XY) { float a = readFloat(); float b = readFloat(); ValueVector ab; ab.push_back(Value(a)); ab.push_back(Value(b)); value = ab; } else if (type == PropertyType::SPRITEFRAME) { std::string spriteSheet = readCachedString(); std::string spriteFile = readCachedString(); SpriteFrame* spriteFrame; if (spriteSheet.empty()) { spriteFile = _CCBRootPath + spriteFile; Texture2D *texture = Director::DirectorInstance->getTextureCache()->addImage(spriteFile); Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); } else { spriteSheet = _CCBRootPath + spriteSheet; SpriteFrameCache* frameCache = SpriteFrameCache::getInstance(); // Load the sprite sheet only if it is not loaded if (_loadedSpriteSheets.find(spriteSheet) == _loadedSpriteSheets.end()) { frameCache->addSpriteFramesWithFile(spriteSheet); _loadedSpriteSheets.insert(spriteSheet); } spriteFrame = frameCache->getSpriteFrameByName(spriteFile); } keyframe->setObject(spriteFrame); } if (!value.isNull()) keyframe->setValue(value); return keyframe; }
void ControllerPlayer::cdImg(float time, std::string name1, std::string name2, Button* but, float scale, MyEnum type) { CallFunc* cding; CallFunc* cded; ccdbut(); switch (type) { case attackcd: { cding = CallFunc::create([&](){attackisCD = true; }); cded = CallFunc::create([&](){attackisCD = false; }); this->scheduleOnce(schedule_selector(ControllerPlayer::oscdbut), 1.0f); PlayerAction(StringUtils::toString(attackType)); this->scheduleOnce(schedule_selector(ControllerPlayer::Cdskill), 0.8f); break; } case skillcd: { cding = CallFunc::create([&](){skillisCD = true; }); cded = CallFunc::create([&](){skillisCD = false; }); this->scheduleOnce(schedule_selector(ControllerPlayer::oacdbut), 1.2f); PlayerAction(StringUtils::toString(skillType)); this->scheduleOnce(schedule_selector(ControllerPlayer::Cdskill), 1.2f); break; } case bigskillcd: { cding = CallFunc::create([&](){ bigisCD = true; }); cded = CallFunc::create([&](){ bigisCD = false; }); this->scheduleOnce(schedule_selector(ControllerPlayer::obscdbut), 2.0f); PlayerAction(StringUtils::toString(skillType)); this->scheduleOnce(schedule_selector(ControllerPlayer::Cdskill), 1.2f); break; } case shangxiancd: { cding = CallFunc::create([&](){ sxisCD = true; }); cded = CallFunc::create([&](){ sxisCD = false; }); this->scheduleOnce(schedule_selector(ControllerPlayer::osxcdbut), 0.6f); m_player->sxskill(); this->scheduleOnce(schedule_selector(ControllerPlayer::Cdskill), 0.6f); break; } } SpriteFrameCache* frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("fight0.plist", "fight0.png"); Point thepoint = but->getPosition(); auto cds = Sprite::createWithSpriteFrameName(name2); cds->setPosition(thepoint); cds->setScale(scale, scale); addChild(cds, 3); auto funk = [cds, but]() { cds->setVisible(false); but->setEnabled(true); }; CallFunc* func = CallFunc::create(funk); auto cd = ProgressTimer::create(Sprite::createWithSpriteFrameName(name1)); cd->setType(ProgressTimer::Type::RADIAL); cd->setPosition(thepoint); cd->setScale(0.74, 0.74); auto to1 = Sequence::create(cding, ProgressTo::create(time, 100), ProgressTo::create(0, 0), func, cded, nullptr); cd->runAction(to1); addChild(cd, 4); }