void Raquet::setColor(ccColor3B color, float duration) { auto colorize = CCTintTo::create(duration, color.r, color.g, color.b); colorize->setTag(colorizeActionTag); sprite->stopActionByTag(colorizeActionTag); sprite->runAction(colorize); }
Node* StageSelect::getItemNode(int i) { auto item = Node::create(); Sprite* item_bk = nullptr; if(i<=fake_overstage) item_bk = Sprite::createWithSpriteFrameName("bt_mission_0.png"); else item_bk = Sprite::createWithSpriteFrameName("bt_mission_1.png"); item->setAnchorPoint(Point::ANCHOR_MIDDLE); item_bk->setPosition(Point(_cellSize.width/2,_cellSize.height/2)); item_bk->setTag(20); item->addChild(item_bk); auto item_hl = Sprite::createWithSpriteFrameName("bt_mission_3.png"); item_hl->setAnchorPoint(Point::ANCHOR_MIDDLE); item_hl->setPosition(Point(_cellSize.width/2,_cellSize.height/2)); item_hl->setTag(30); item_hl->setVisible(false); item->addChild(item_hl); if(i == _selectItem) item_hl->setVisible(true); else item_hl->setVisible(false); if(_noTouch && i==_selectItem) item_hl->setVisible(true); std::string stage_text_str = s_gameStrings.mainMenu->stagetext + " - " + Value(i+1).asString(); auto stage_text = TextSprite::create(stage_text_str,GameConfig::defaultFontName,GameConfig::defaultFontSize); if(i<fake_overstage) stage_text->setColor(Color3B(230,230,230)); else stage_text->setColor(Color3B(80,80,80)); if (_noTouch && i == _selectItem) { stage_text->setColor(DIY_COLOR_BLUE5); } stage_text->setAnchorPoint(Point::ANCHOR_MIDDLE); stage_text->setPosition(Point(_cellSize.width/2,_cellSize.height/2)); stage_text->setTag(40); item->addChild(stage_text); auto sp_new = Sprite::createWithSpriteFrameName("icon_new.png"); sp_new->setAnchorPoint(Point::ANCHOR_MIDDLE); sp_new->setPosition(Point(_cellSize.width/2+150,_cellSize.height/2)); sp_new->setTag(50); sp_new->setVisible(false); item->addChild(sp_new); if (fake_overstage == i && s_playerConfig.overstage<50) { sp_new->setVisible(true); } auto ball = RotateBall::createWithIdx(i); ball->setAnchorPoint(Point::ANCHOR_MIDDLE); ball->setPosition(100, 50); ball->setTag(60); item->addChild(ball); ball->setRotate(true); auto ball_mask = Sprite::createWithSpriteFrameName("icon_planet_mask.png"); ball_mask->setOpacity(120); ball_mask->setScale(0.8f); ball_mask->setAnchorPoint(Point::ANCHOR_MIDDLE); ball_mask->setPosition(100, 50); ball_mask->setTag(70); item->addChild(ball_mask); if(i<=fake_overstage) ball_mask->setVisible(false); else ball_mask->setVisible(true); return item; }
void KeyboardEventDispatchingPerfTest::generateTestFunctions() { TestFunction testFunctions[] = { { "keyboard-scenegraph", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; // Create new nodes listen to keyboard event for (int i = 0; i < this->_quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(1000 + i); this->addChild(node); this->_nodes.push_back(node); dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); } _lastRenderedCount = _quantityOfNodes; } EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&event); CC_PROFILER_STOP(this->profilerName()); } } , { "keyboard-fixed", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; for (int i = 0; i < this->_quantityOfNodes; ++i) { auto l = listener->clone(); this->_fixedPriorityListeners.push_back(l); dispatcher->addEventListenerWithFixedPriority(l, i+1); } _lastRenderedCount = _quantityOfNodes; } EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&event); CC_PROFILER_STOP(this->profilerName()); } } , }; for (const auto& func : testFunctions) { _testFunctions.push_back(func); } }
LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); // create and initialize a Label this->_labelShouldRetain = Label::createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, TextHAlignment::CENTER, size.width/1.5); this->_labelShouldRetain->setAnchorPoint(Point::ANCHOR_MIDDLE); this->_labelShouldRetain->retain(); this->_arrowsBarShouldRetain = Sprite::create("Images/arrowsBar.png"); this->_arrowsBarShouldRetain->retain(); this->_arrowsShouldRetain = Sprite::create("Images/arrows.png"); this->_arrowsShouldRetain->retain(); MenuItemFont::setFontSize(20); auto longSentences = MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, NULL); stringMenu->alignItemsVertically(); longSentences->setColor(Color3B::RED); _lastSentenceItem = longSentences; longSentences->setTag(LongSentences); lineBreaks->setTag(LineBreaks); mixed->setTag(Mixed); MenuItemFont::setFontSize(30); auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto center = MenuItemFont::create("Center", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); auto alignmentMenu = Menu::create(left, center, right, NULL); alignmentMenu->alignItemsHorizontallyWithPadding(alignmentItemPadding); center->setColor(Color3B::RED); _lastAlignmentItem = center; left->setTag(LeftAlign); center->setTag(CenterAlign); right->setTag(RightAlign); // position the label on the center of the screen this->_labelShouldRetain->setPosition(Point(size.width/2, size.height/2)); this->_arrowsBarShouldRetain->setVisible(false); float arrowsWidth = (ArrowsMax - ArrowsMin) * size.width; this->_arrowsBarShouldRetain->setScaleX(arrowsWidth / this->_arrowsBarShouldRetain->getContentSize().width); this->_arrowsBarShouldRetain->setPosition(Point(((ArrowsMax + ArrowsMin) / 2) * size.width, this->_labelShouldRetain->getPosition().y)); this->snapArrowsToEdge(); stringMenu->setPosition(Point(size.width/2, size.height - menuItemPaddingCenter)); alignmentMenu->setPosition(Point(size.width/2, menuItemPaddingCenter+15)); this->addChild(this->_labelShouldRetain); this->addChild(this->_arrowsBarShouldRetain); this->addChild(this->_arrowsShouldRetain); this->addChild(stringMenu); this->addChild(alignmentMenu); }
bool GameMap::init() { if(!Node::init()) return false; //Ìí¼Óש¿é std::string block_file; std::string npc_file; switch(level) { case SPRING: block_file="block_spring.png"; npc_file="lvshuiling.png"; break; case WINTER: block_file="block_winter.png"; npc_file="lanmogu.png"; break; } std::string star_file="star.png"; std::string tool_file="accelerate.png"; //ÊÖ¶¯´î½¨µØͼ£¬Ã»ÓмÓÈ뼴ʱ¼ÆËã~ //1²ã for(int i=0;i<10;i++) { if(i!=3&&i!=4&&i!=7&&i!=8) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+1*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } } //2²ã for(int i=0;i<10;i++) { if(i==2||i==5||i==6) { //Ìí¼Ó¹ÖÎï auto npc=Sprite::create(npc_file); npc->setTag(NPC); npc->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+2*BLOCK_SIZE); auto npcBody=PhysicsBody::createBox(npc->getContentSize()); npcBody->setDynamic(false); npcBody->setContactTestBitmask(1); npcBody->getShape(0)->setRestitution(0); npc->setPhysicsBody(npcBody); this->addChild(npc); } if(i==3) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+1*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } } //3²ã for(int i=0;i<10;i++) { if(i!=0&&i!=3&&i!=4) { //Ìí¼ÓÐÇÐÇ auto star1=Sprite::create(star_file); star1->setTag(STAR); star1->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody1=PhysicsBody::createBox(star1->getContentSize()); starBody1->setDynamic(false); starBody1->setContactTestBitmask(1); starBody1->getShape(0)->setRestitution(0.0f); star1->setPhysicsBody(starBody1); this->addChild(star1); auto star2=Sprite::create(star_file); star2->setTag(STAR); star2->setPosition(PICKUP_SIZE/2*3+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody2=PhysicsBody::createBox(star2->getContentSize()); starBody2->setDynamic(false); starBody2->setContactTestBitmask(1); starBody2->getShape(0)->setRestitution(0.0f); star2->setPhysicsBody(starBody2); this->addChild(star2); } } //4²ã for(int i=0;i<10;i++) { if(i==3||i==4) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+4*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } if(i==8) { auto star1=Sprite::create(star_file); star1->setTag(STAR); star1->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody1=PhysicsBody::createBox(star1->getContentSize()); starBody1->setDynamic(false); starBody1->setContactTestBitmask(1); starBody1->getShape(0)->setRestitution(0.0f); star1->setPhysicsBody(starBody1); this->addChild(star1); auto star2=Sprite::create(star_file); star2->setTag(STAR); star2->setPosition(PICKUP_SIZE/2*3+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody2=PhysicsBody::createBox(star2->getContentSize()); starBody2->setDynamic(false); starBody2->setContactTestBitmask(1); starBody2->getShape(0)->setRestitution(0.0f); star2->setPhysicsBody(starBody2); this->addChild(star2); } if(i==6) { //Ìí¼ÓµÀ¾ß auto tool=Sprite::create(tool_file); tool->setTag(TOOL); tool->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto toolBody=PhysicsBody::createBox(tool->getContentSize()); toolBody->setDynamic(false); toolBody->setContactTestBitmask(1); toolBody->getShape(0)->setRestitution(0.0f); tool->setPhysicsBody(toolBody); this->addChild(tool); } } //Æô¶¯µ÷¶ÈÆ÷£¬µØͼ¹öÆÁ this->schedule(schedule_selector(GameMap::mapUpdate),0.01f); return true; }
bool PlayScene::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto height = visibleSize.height; auto width = visibleSize.width; auto background = Sprite::create("res/scr1.png"); background->setPosition(width/2, height/2); background->setScale(102.6); this->addChild(background,0); myplane=Sprite::create("res/plpl.png"); myplane->setPosition(300,300); auto body = PhysicsBody::createBox(Size(70, 40)); body->setMass(1000); myplane->setPhysicsBody(body); addChild(myplane); auto dispatcher = Director::getInstance()->getEventDispatcher(); auto myListener = EventListenerTouchOneByOne::create(); //如果不加入此句消息依旧会向下传递 myListener->setSwallowTouches(true); touchdown = false; float playfield_width = visibleSize.width * 2.0; // make the x-boundry 2 times the screen width float playfield_height = visibleSize.height * 2.0; // make the y-boundry 2 times the screen height Point center = Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y); //note : since bounddries are 2 times the screen size calculate new center point // this->runAction(Follow::create(myplane) ); myplane->getPhysicsBody()->setVelocityLimit(200); fire = ParticleSun::create(); fire->setTexture(Director::getInstance()->getTextureCache()->addImage("res/fire.png")); // fire->setGravity(Vec2(-300,0)); addChild(fire); myplane->getPhysicsBody()->getPosition(); myListener->onTouchBegan = [=](Touch* touch,Event* event) { //some check CCLOG("touchbegin"); touchdown = true; if (1) { return true; } return false; }; for (int i = 0; i<0; i++) { auto x = arc4random()%(int)width; auto y = arc4random()%(int)height; Sprite* rock = Sprite::create("res/debris.png"); rock->setPosition(x,y); rock->setScale(0.3); addChild(rock); rock->setPosition(x,y); auto rockbody = PhysicsBody::createCircle(30); // rockbody->setDynamic(false); auto vx =arc4random()%300; auto vy =arc4random()%300; // rockbody->setVelocity(Vec2(vx-150,vy-150)); rockbody->setMass(1000); rock->setPhysicsBody(rockbody); } myListener->onTouchMoved = [=](Touch* touch,Event* event) { }; myListener->onTouchEnded = [=](Touch* touch,Event* event) { touchdown = false; auto angle = myplane->getPhysicsBody()->getRotation(); auto angle1 = (angle+0) /180*M_PI; auto angle2 = (angle+90) /180*M_PI; // myplane->getPhysicsBody()->applyForce(Vec2(-600000*cos(angle1),-600000*sin(angle1))); // myplane->getPhysicsBody()->applyForce(Vec2(-400000*cos(angle2),-400000*sin(angle2))); myplane->getPhysicsBody()->resetForces(); }; dispatcher->addEventListenerWithSceneGraphPriority(myListener,this); auto edgeSp = Sprite::create(); auto body2 = PhysicsBody::createEdgeBox(Size(visibleSize.width*30,visibleSize.height)); edgeSp->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); edgeSp->setPhysicsBody(body2); this->addChild(edgeSp); edgeSp->setTag(0); scheduleUpdate(); return true; }
void Player::update(float dt) { //////////爆風に当たってたらゲームオーバーにする/////////// if (scene->mapcontrol->getblock(getPosition())->firenull() == false) { gameover(); } ///////enterキーでボム設置/////////////// if (obsevekey->getkey((Observekey::Key)playerkey.bomset) == 2 && bomcon->getChildrenCount()<maximumbom) { bomset(); } //////主人公移動//////////////////////// //主人公がmoveアニメーションしていないとき if (getActionByTag(1) == nullptr) { static int x = 0, y = 0; if (obsevekey->getkey((Observekey::Key)playerkey.right) != 0) { if (x == 16 && y == 0) {} else { setTexture("シロボン右.png"); stopActionByTag(2); runAction(action[RIGHT]); x = 16; y = 0; } } else if (obsevekey->getkey((Observekey::Key)playerkey.left) != 0) { if (x == -16 && y == 0) {} else { setTexture("シロボン左.png"); stopActionByTag(2); runAction(action[LEFT]); x = -16; y = 0; } } else if (obsevekey->getkey((Observekey::Key)playerkey.up) != 0) { if (x == 0 && y == 16) {} else { setTexture("シロボン前.png"); stopActionByTag(2); runAction(action[FRONT]); x = 0; y = 16; } } else if (obsevekey->getkey((Observekey::Key)playerkey.down) != 0) { if (x == 0 && y == -16) {} else { setTexture("シロボン後.png"); stopActionByTag(2); runAction(action[BACK]); x = 0; y = -16; } } else { stopActionByTag(2); x = 0; y = 0; return; } //移動先に障害物がないとき if (scene->mapcontrol->getblock(Vec2(getPositionX() + x,getPositionY() + y))->obstaclecheck() == false) { //1ブロック分移動 auto move = MoveBy::create(speed, Vec2(x, y)); move->setTag(1); runAction(move); } } }
// on "init" you need to initialize your instance bool ChooserScene::init(int _offset) { offset = _offset; ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); string title = vector < string > { "Moon", "Mars", "Uranus" }[GameSettings::CurrentEpisode]; auto hooker = TopAnchor::create(); addChild(hooker, 1); auto episodetitle = Label::createWithTTF(title, FANCY_TTF, 60.0f); episodetitle->setHorizontalAlignment(TextHAlignment::CENTER); episodetitle->setPosition(VCP(0.5f, 0.9f)); hooker->addChild(episodetitle); auto pMenu = Menu::create(); pMenu->setPosition(Point::ZERO); hooker->addChild(pMenu, 1); auto btnMenu = MAKEBUTTON("btnMenuUp", "btnMenuDn", ChooserScene::btnMenuPressed); btnMenu->setPosition(VCP(0, 1)); btnMenu->setAnchorPoint(Point(-0.5, 1.5)); btnMenu->setScale(1.3f); pMenu->addChild(btnMenu); auto pLevels = Menu::create(); pLevels->setPosition(Point::ZERO); pLevels->setTag(0); hooker->addChild(pLevels); const float startX = 0.2f; const float startY = 0.25f; auto bSprite = Sprite::createWithSpriteFrameName("circle"); auto contentsize = bSprite->getContentSize(); float off = 1.0f - (2.0f * startX); off /= (float) (lCount - 1); float offy = 1.0f - (startY * 2.0f); offy /= (float) (rCount - 1); log("Unlocked Level ID:" + nToString(GameSettings::GetUnlockedLevelId())); float y = startY; GLubyte cR = 255; for (int r = 0; r < rCount; r++) { float x = startX; GLubyte cG = 200; // static_cast<GLubyte>(200.0f * (float) offset / (float) GameSettings::MaximumLevelId); GLubyte cB = 20; // +200 - static_cast<GLubyte>(200.0f * (float) offset / (float) GameSettings::MaximumLevelId);; for (int i = 0; i < lCount; i++) { int levelId = offset + (rCount - (r + 1)) * lCount + i; if (levelId >= GameSettings::GetMaximumLevelId()) break; Node* btn; if (levelId <= GameSettings::GetUnlockedLevelId()) { btn = MAKEBUTTON("circle", "circleDn", ChooserScene::btnLevelPressed); btn->setTag(100 + levelId); pLevels->addChild(btn); blobs.push_back(btn); btn->setPosition(VCP(x, y)); Label* lbl = Label::createWithSystemFont(nToString(levelId + 1).c_str(), "Consolas", 28.0); lbl->setColor(Color3B::WHITE); lbl->setPosition(VCP(x, y)); numbers.push_back(lbl); this->addChild(lbl, 1); btn->setColor(Color3B(cR, cG, cB)); } else { btn = Sprite::createWithSpriteFrameName("circleLk"); btn->setTag(100 + levelId); hooker->addChild(btn); blobs.push_back(btn); btn->setPosition(VCP(x, y)); } btn->setScale(0.8f); #if ENABLE_IAD //btn->setScale(0.8f); #endif cG *= 0.5; cB *= 1.7; cB = cB > 255 ? 255 : cB; x += off; } cR *= 0.7; y += offy; } if (offset > 0) { auto backBtn = MAKEBUTTON("btnBackUp", "btnBackDn", btnBackPressed); backBtn->setPosition(CP(0.1f, 0.1f)); backBtn->setScale(1.3f); pMenu->addChild(backBtn); } if (offset + lCount * rCount < GameSettings::GetMaximumLevelId()) { auto nextBtn = MAKEBUTTON("btnNextUp", "btnNextDn", btnNextPressed); nextBtn->setPosition(CP(0.9f, 0.1f)); nextBtn->setScale(1.3f); pMenu->addChild(nextBtn); } schedule(schedule_selector(ChooserScene::bloop), 2.0f, kRepeatForever, 4.0f); auto keyboard = EventListenerKeyboard::create(); keyboard->onKeyReleased = CC_CALLBACK_2(ChooserScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboard, this); return true; }
Head_ParticalEffect void addParticalToHead(Node* node) { Vec2 pos[4]; pos[0] = Vec2(5, 75); pos[1] = Vec2(75, 75); pos[2] = Vec2(75, 5); pos[3] = Vec2(5, 5); for (int i = 0; i < 2; i++) { auto partNode = ParticleSystemQuad::createWithTotalParticles(60); partNode->setTexture(TextureCache::getInstance()->addImage("GameUI/CommonUI/fire.png"));//设置粒子图 partNode->setDuration(-1);//发射时长 // life of particles partNode->setLife(0.5f);//粒子生命 partNode->setLifeVar(0.1f); partNode->setEmissionRate(partNode->getTotalParticles() / partNode->getLife());//发射器发射频率 partNode->setPositionType(ParticleSystem::PositionType::FREE);//设置发射器的跟随模式 // color of particles partNode->setStartColor(ccc4f(0.76f, 0.25f, 0.12f, 1.0f));//起始颜色 partNode->setStartColorVar(ccc4f(0.1f, 0.1f, 0.1f, 0.0f)); partNode->setEndColor(ccc4f(1.0f, 1.0f, 1.0f, 1.0f));//结束颜色 partNode->setEndColorVar(ccc4f(0.1f, 0.1f, 0.1f, 0.1f)); // size, in pixels partNode->setStartSize(15);//粒子大小 partNode->setStartSizeVar(3); partNode->setEndSize(0); partNode->setEndSizeVar(3); // angle partNode->setAngle(0);//发射器角度 partNode->setAngleVar(0); // speed of particles partNode->setSpeed(0);//粒子速度 partNode->setSpeedVar(0); // emitter position partNode->setPosVar(ccp(0, 0));//发射器位置变化 partNode->setBlendAdditive(true); node->addChild(partNode); partNode->setTag(PARTICALTAG); auto move0 = MoveTo::create(1.f, pos[0]); auto move1 = MoveTo::create(1.f, pos[1]); auto move2 = MoveTo::create(1.f, pos[2]); auto move3 = MoveTo::create(1.f, pos[3]); if (i == 0) { partNode->setPosition(pos[0]); partNode->runAction(RepeatForever::create(Sequence::create(move1, move2, move3, move0, nullptr))); } else { partNode->setPosition(pos[2]); partNode->runAction(RepeatForever::create(Sequence::create(move3, move0, move1, move2, nullptr))); } } }
bool ActionScene::init() { if (! Scene::init()) { return false; } // auto bkqSpr = Sprite::create("bkq1.png"); bkqSpr->setPosition(DISPLAY_CX, DISPLAY_CY); bkqSpr->setTag(111); bkqSpr->setName("bkq"); addChild(bkqSpr); frmTime = 0; //scheduleUpdate(); //to by //auto action = MoveBy::create(2.0f, Vec2(200, 0)); //auto action = MoveTo::create(2.0f, Vec2(200, 0)); //auto action = JumpTo::create(2.0f, Vec2(DISPLAY_CX + 200, DISPLAY_CY), 100, 5); //auto action = JumpBy::create(0.5f, Vec2(200, 0), 200, 1); //±´Èû¶ûÇúÏß /* ccBezierConfig bezierCfg; bezierCfg.endPosition = Point(DISPLAY_CX + 400, DISPLAY_CY); bezierCfg.controlPoint_1 = Point(DISPLAY_CX , DISPLAY_CY +200); bezierCfg.controlPoint_2 = Point(DISPLAY_CX + 500, DISPLAY_CY - 200); auto action = CCBezierTo::create(2.0f,bezierCfg); */ //auto actionScale = ScaleTo::create(2.0f,0.5); //auto actionRotate = RotateBy::create(2.0f, 180); //auto action = Sequence::create(actionScale,actionRotate,NULL); //auto action = Spawn::create(actionScale, actionRotate, NULL); /**/ /* auto moveActionRight = MoveBy::create(1.0f, Vec2(200, 0)); auto moveActionLeft = moveActionRight->reverse();//MoveBy::create(1.0f, Vec2(-200, 0)); auto flipAction = FlipX::create(true); auto flipAction1 = FlipX::create(false); auto delayAction = DelayTime::create(1.0f); auto seqAction = Sequence::create(moveActionRight, delayAction,flipAction , moveActionLeft, delayAction, flipAction1, NULL); //auto action = Repeat::create(seqAction, 20); auto action = RepeatForever::create(seqAction); */ //FADE //auto action = FadeOut::create(5.f); //tint //auto action = TintBy::create(3.f, 100, -30, 50); //blink //auto action = Blink::create(3.f, 10); //func auto moveAction = MoveBy::create(2.f, Vec2(200, 0)); //auto action = Sequence::create(moveAction, // CallFunc::create(CC_CALLBACK_0(ActionScene::endFunction,this)) // , NULL); auto action = Sequence::create(moveAction, CallFunc::create(std::bind(&ActionScene::endFunction,this)), NULL); bkqSpr->runAction(action); return true; }
bool Help::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //背景精灵 if (getPass() == 1) { auto bg1 = Sprite::create("help_bg1.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 2) { auto bg1 = Sprite::create("help_bg2.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 3){ auto bg1 = Sprite::create("help_bg3.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 4) { auto bg1 = Sprite::create("help_bg4.png"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 5) { auto bg1 = Sprite::create("help_bg4.png"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } auto MagicItem = MenuItemImage::create("continue.png", "continue2.png", CC_CALLBACK_1(Help::menuContinueCallback, this)); MagicItem->setPosition(Vec2(visibleSize.width - MagicItem->getContentSize().width - 20, MagicItem->getContentSize().height * 2)); MagicItem->setAnchorPoint(Vec2(0.5, 0.5)); auto menu = Menu::create(MagicItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); return true; }
bool StartGame:: init(){ if (!Layer::init()) { return false; } itemArray=__Array::create(); itemArray->retain(); int k=arc4random()%6+1; std::string str= StringUtils::format("mineBG%d.png",k); auto visibleSize=Director::getInstance()->getVisibleSize(); auto sprite=Sprite::create(str); sprite->setPosition(visibleSize.width/2,visibleSize.height/2); this->addChild(sprite); //离子 ParticleSystemQuad* quad = ParticleSystemQuad::create("fengye.plist"); quad->setBlendAdditive(true); quad->setAutoRemoveOnFinish(true); quad->setPosition(Vec2(400, 300)); this->addChild(quad); //黄金 char a[50]; sprintf(a, "%d",score[level-1]); auto sprite1=Sprite::create("Gold.png"); sprite1->setPosition(visibleSize.width/2-200,visibleSize.height/2+130); auto lable1=Label::createWithSystemFont(a, "fonts/Marker Felt.ttf ", 28); lable1->setTextColor(Color4B::GREEN); lable1->setPosition(visibleSize.width/2-150,visibleSize.height/2+130); lable1->setTag(10); this->addChild(lable1); this->addChild(sprite1); //钱 auto sprite2=Sprite::create("rmbImage.png"); sprite2->setPosition(visibleSize.width/2-200,visibleSize.height/2+90); auto lable2=Label::createWithSystemFont("0", "fonts/Marker Felt.ttf ", 28); lable2->setPosition(visibleSize.width/2-150,visibleSize.height/2+90); lable2->setTag(20); lable2->setTextColor(Color4B::RED); this->addChild(lable2); this->addChild(sprite2); //矿工 auto sprite3=Sprite::create("miner_0707.png"); sprite3->setPosition(visibleSize.width/2+180,visibleSize.height/2+130); char c[50]; sprintf(c, "%d",level); auto lable3=Label::createWithSystemFont(c, "fonts/Marker Felt.ttf ", 28); lable3->setPosition(visibleSize.width/2+220,visibleSize.height/2+130); lable3->setTag(30); lable3->setTextColor(Color4B::GREEN); this->addChild(lable3); this->addChild(sprite3); char d[50]; sprintf(d, "%d",totalTime[level-1]); auto sprite4=Sprite::create("clockPlate.png"); sprite4->setTag(4); sprite4->setPosition(visibleSize.width/2+180,visibleSize.height/2+90); auto lable4=Label::createWithSystemFont(d, "fonts/Marker Felt.ttf ", 28); lable4->setPosition(visibleSize.width/2+220,visibleSize.height/2+90); lable4->setTag(40); lable4->setTextColor(Color4B::GREEN); this->addChild(lable4); this->addChild(sprite4); auto item=MenuItemImage::create("qianglishui.png", "qianglishui.png"); auto item1=MenuItemImage::create("qianglishui.png", "qianglishui.png"); toggle=MenuItemToggle::create(); toggle->addSubItem(item); toggle->addSubItem(item1); toggle->setScale(0.5); toggle->setSelectedIndex(0); toggle->setCallback([this](Ref*){ //减少PowerWater数量 auto lable=(Label*)this->getChildByTag(50); int num= atoi(lable->getString().c_str()); if (num!=0){ Water--; miner->setScale(1.5); //this->schedule(schedule_selector(StartGame::changeSelect),8); this->schedule(CC_CALLBACK_1(StartGame::changeSelect,this), 8, "changeSelect"); lable->setString(StringUtils::format("%d",Water)); this->testCollin(1.0); }else if(num==0){ toggle->setSelectedIndex(0); log("%d",toggle->getSelectedIndex()); } }); menu=Menu::create(toggle, NULL); menu->setPosition(Vec2(visibleSize.width/2+180, visibleSize.height/2+50)); std::string str1= StringUtils::format("%d",Water); lable5=Label::createWithSystemFont(str1,"fonts/Marker Felt.ttf", 28); lable5->setPosition(Vec2(visibleSize.width/2+220, visibleSize.height/2+50)); lable5->setTag(50); lable5->setTextColor(Color4B::GREEN); this->addChild(lable5); this->addChild(menu); if (Boom) { auto item2=MenuItemImage::create("article_2001.png", "article_2001.png"); item2->setScale(1.3); item2->setCallback(CC_CALLBACK_0(StartGame::removeBoom, this)); auto menu=Menu::create(item2,NULL); menu->setPosition(Vec2(visibleSize.width/2+220, visibleSize.height/2+10)); menu->setTag(60); this->addChild(menu); } miner=new Miner(); miner->setPosition(visibleSize.width/2,visibleSize.height/2); this->addChild(miner); hook=Hook::createHook(); hook->setAnchorPoint(Point(0.5, 1)); hook->setPosition(visibleSize.width/2-5,visibleSize.height/2-20); hook->rotate(); this->addChild(hook,1); //添加石头 黄金 this->item(); auto dispather=Director::getInstance()->getEventDispatcher(); auto listener=EventListenerTouchOneByOne::create(); listener->onTouchBegan=CC_CALLBACK_2(StartGame::onTouchBegan, this); //点击事件 listener->onTouchEnded=[this](Touch *touch, Event *unused_event){ if(hook->getPosition().x==235 && hook->getPosition().y == 140){ hook->stopAllActions(); hook->runTarget(); } }; dispather->addEventListenerWithSceneGraphPriority(listener ,this); this->schedule(CC_CALLBACK_1(StartGame::consumeTime,this), 1, "consumTime"); this->schedule(schedule_selector(StartGame::testCollin), 0.01); return true; }
bool LevelTwentytwo::init() { if (!Layer::init()) { return false; } // 用于解决刚体穿透问题 this->scheduleUpdate(); // 计时器 this->schedule(schedule_selector(LevelTwentytwo::timeCounter), 1.0f); auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); // 加载背景贴图 auto spriteBg = Sprite::create("background.png"); spriteBg->setAnchorPoint(Vec2::ZERO); spriteBg->setPosition(Vec2::ZERO); addChild(spriteBg); ballOne = Sprite::createWithSpriteFrameName("hero.png"); ballOne->setPosition(visibleSize.width / 2.0f, ballOne->getContentSize().height); auto ballBodyOne = PhysicsBody::createCircle(ballOne->getContentSize().width / 2, PHYSICSBODY_MATERIAL_DEFAULT); //是否设置物理为静态 //ballBodyOne->setDynamic(false); //设置物理的恢复力 ballBodyOne->getShape(0)->setRestitution(0.5f); //设置物体的摩擦力 ballBodyOne->getShape(0)->setFriction(0.0f); ballBodyOne->getShape(0)->setDensity(0.3f); // 设置质量 质量等于密度乘以面积 //ballBodyOne->getShape(0)->setMass(5000); // 设置物体是否受重力系数影响 ballBodyOne->setGravityEnable(true); ballBodyOne->setCategoryBitmask(1);// 分类掩码 ballBodyOne->setCollisionBitmask(1 | 2 | 4 | 8);// 碰撞掩码 ballBodyOne->setContactTestBitmask(8);// 接触测试掩码 // 把物体添加到精灵 ballOne->setPhysicsBody(ballBodyOne); this->addChild(ballOne); auto girl = Sprite::createWithSpriteFrameName("girl.png"); girl->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f + 250.0f); auto girlBody = PhysicsBody::createCircle(girl->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); girlBody->setDynamic(false); girlBody->setGravityEnable(false); girlBody->setCategoryBitmask(8); girlBody->setCollisionBitmask(1); girlBody->setContactTestBitmask(1); girl->setPhysicsBody(girlBody); this->addChild(girl); //创建一个盒子,用来碰撞 auto edgeSpace = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); boundBody->getShape(0)->setFriction(0.0f); boundBody->getShape(0)->setRestitution(1.0f); edgeSpace->setPhysicsBody(boundBody); edgeSpace->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); this->addChild(edgeSpace); edgeSpace->setTag(0); boundBody->setCategoryBitmask(4); boundBody->setCollisionBitmask(1 | 2 | 4); boundBody->setContactTestBitmask(0); // 随机位置 int index = CCRANDOM_0_1() * 4; auto suiji1 = 0; auto suiji2 = 0; auto suiji3 = 0; switch (index) { case 0: suiji1 = CCRANDOM_0_1() * 240; suiji2 = -CCRANDOM_0_1() * 100; suiji3 = -CCRANDOM_0_1() * 150; break; case 1: suiji1 = -CCRANDOM_0_1() * 240; suiji2 = -CCRANDOM_0_1() * 100; suiji3 = -CCRANDOM_0_1() * 150; break; case 2: suiji1 = -CCRANDOM_0_1() * 240; suiji2 = CCRANDOM_0_1() * 100; suiji3 = CCRANDOM_0_1() * 150; break; case 3: suiji1 = CCRANDOM_0_1() * 240; suiji2 = CCRANDOM_0_1() * 100; suiji3 = CCRANDOM_0_1() * 150; break; default: break; } // 创建yuan auto white1 = Sprite::createWithSpriteFrameName("white2.png"); white1->setPosition(visibleSize.width / 2.0f + 200.0f, visibleSize.height / 2.0f - 150.0f); auto whiteBody1 = PhysicsBody::createCircle(white1->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1->setDynamic(false); whiteBody1->setCategoryBitmask(4); whiteBody1->setCollisionBitmask(1 | 2 | 4); whiteBody1->setContactTestBitmask(0); white1->setPhysicsBody(whiteBody1); this->addChild(white1); // 正方形 auto white1_2 = Sprite::createWithSpriteFrameName("white1.png"); white1_2->setPosition(visibleSize.width / 2.0f - 200.0f, visibleSize.height / 2.0f + 150.0f); auto whiteBody1_2 = PhysicsBody::createBox(white1_2->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1_2->setDynamic(false); whiteBody1_2->setCategoryBitmask(4); whiteBody1_2->setCollisionBitmask(1 | 2 | 4); whiteBody1_2->setContactTestBitmask(0); white1_2->setPhysicsBody(whiteBody1_2); this->addChild(white1_2); // 创建三角形 Vec2 arr[] = { Vec2(-16.50000, 36.00000), Vec2(35.50000, -15.00000), Vec2(-34.00000, -32.50000) }; auto white3 = Sprite::createWithSpriteFrameName("white3.png"); white3->setPosition(visibleSize.width / 2.0f + suiji3, visibleSize.height / 2.0f + suiji2); auto whiteBody3 = PhysicsBody::createPolygon(arr, 3, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody3->setDynamic(false); whiteBody3->setCategoryBitmask(4); whiteBody3->setCollisionBitmask(1 | 2 | 4); whiteBody3->setContactTestBitmask(0); white3->setPhysicsBody(whiteBody3); this->addChild(white3); auto rotation_1 = RotateBy::create(2, 360); auto rotationback_1 = rotation_1->reverse(); auto seq1 = Sequence::create(rotation_1, rotationback_1, nullptr); auto repeat1 = RepeatForever::create(seq1); white1_2->runAction(repeat1); auto yuantong0 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong0->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height + yuantong0->getContentSize().height / 2.0f)); auto yuantongBody = PhysicsBody::createBox(yuantong0->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody->setDynamic(false); yuantongBody->setCategoryBitmask(4); yuantongBody->setCollisionBitmask(1 | 2 | 4); yuantongBody->setContactTestBitmask(0); yuantong0->setPhysicsBody(yuantongBody); this->addChild(yuantong0); auto yuantong1 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong1->setPosition(Vec2(visibleSize.width / 2.0f - yuantong1->getContentSize().width / 2 * 3, visibleSize.height + yuantong1->getContentSize().height / 2.0f)); auto yuantongBody1 = PhysicsBody::createBox(yuantong1->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody1->setDynamic(false); yuantongBody1->setCategoryBitmask(4); yuantongBody1->setCollisionBitmask(1 | 2 | 4); yuantongBody1->setContactTestBitmask(0); yuantong1->setPhysicsBody(yuantongBody1); this->addChild(yuantong1); auto moveby0 = MoveBy::create(0.5f, Vec2(0, -90)); auto moveby0back = moveby0->reverse(); auto easein = EaseBackIn::create(moveby0); auto seq0 = Sequence::create(easein, CallFuncN::create(CC_CALLBACK_1(LevelTwentytwo::callbackC, this)), moveby0back, nullptr); auto repeat0 = RepeatForever::create(seq0); yuantong0->runAction(repeat0); auto moveby1 = MoveBy::create(1.0f, Vec2(0, -90)); auto moveby1back = moveby1->reverse(); auto easein1 = EaseBackIn::create(moveby1); auto yuantongseq1 = Sequence::create(easein1, CallFuncN::create(CC_CALLBACK_1(LevelTwentytwo::callbackC, this)), moveby1back, nullptr); auto yuantongrepeat1 = RepeatForever::create(yuantongseq1); yuantong1->runAction(yuantongrepeat1); listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [=](Touch* touch, Event* event){ Vec2 force = Vec2::ZERO; force = Vec2(0, 50000.0f); ballOne->getPhysicsBody()->applyImpulse(force); return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // 时间显示文本 test = LabelAtlas::create(StringUtils::toString(nTimes), "1.png", 14, 21, '0'); test->setScale(2.0f); test->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test->setPosition(Vec2(test->getContentSize().width + 10, visibleSize.height - test->getContentSize().height)); this->addChild(test); test2 = LabelAtlas::create(StringUtils::toString(newTimes), "1.png", 14, 21, '0'); test2->setScale(2.0f); test2->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test2->setPosition(Vec2(visibleSize.width - test2->getContentSize().width - 10, visibleSize.height - test2->getContentSize().height)); this->addChild(test2); return true; }
void MakeItemUI::UpdateUI() { auto layout_Template = m_RootWidget->getChildByName<Layout*>("Layout_Template"); //有新建筑可建或有建筑可建 auto layout_Item_Template = layout_Template->getChildByName<Layout*>("Layout_Item"); auto layout_Center = m_RootWidget->getChildByName<Layout*>("Layout_Center"); auto lView_List = layout_Center->getChildByName<ListView*>("LView_List"); vector<pair<int, Value>> viv; //每次清空 子控件 lView_List->removeAllChildren(); vector<pair<int, Value>> viv_MakeItem; ValueMap* vm_MakeItem = &(UserData::getInstance()->GetUserData(UserDataEnum::MakeItem)->asValueMap()); UserData::getInstance()->VMSKToVIV_Sort(vm_MakeItem, &viv_MakeItem); for (auto iter = viv_MakeItem.begin(); iter != viv_MakeItem.end(); iter++) { auto cfgId = iter->first; if(UserData::getInstance()->Check_VI_Fun(UserDataEnum::OnlyItemList, Value(cfgId))) { continue; } auto layout_Item = layout_Item_Template->clone(); layout_Item->setVisible(true); lView_List->addChild(layout_Item); CfgDataRow dataRow(cfgId); auto langId = dataRow.GetValue(CfgField::Name)->asInt(); auto langText = MultiLanguage::getInstance()->GetText(langId); auto btn_Name = layout_Item->getChildByName<Button*>("Btn_Name"); btn_Name->setTitleText(langText.c_str()); btn_Name->getChildByName<ImageView*>("Sprite_New")->setVisible(iter->second.asBool()); UIUtils::getInstance()->addMakeBatches(btn_Name, this, cfgId); btn_Name->addClickEventListener([this, cfgId, btn_Name](Ref* sender) { if (btn_Name->getTag() == BTN_IS_LONGBTN) { btn_Name->setTag(BTN_NOT_LONGBTN); return; } CfgDataRow dataRow(cfgId); auto vmi_Price = dataRow.GetValue(CfgField::MaterialID_M)->asIntMultiKeyMap(); vector<pair<int, int> > lackData; bool delResutl = UserData::getInstance()->DeleteStorehouseData(&vmi_Price, &lackData); if (delResutl) { makeItemEvent(cfgId); MsgListNode::getInstance()->NewMsg(cfgId, 1, CfgField::Schedule); UpdateUI(); }else { int totalNum = UIUtils::getInstance()->getLackCostDiamond(&lackData); string showText = StringUtils::format(MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::Diamond_ToGet).c_str(), totalNum) + MultiLanguage::getInstance()->GetText(dataRow.GetValue(CfgField::Name)->asInt()); UIUtils::getInstance()->addLeadBuyLayer(this, showText, totalNum, [=]() { UIUtils::getInstance()->costUpgNeededItem(&vmi_Price, &lackData); makeItemEvent(cfgId); MsgListNode::getInstance()->NewMsg(cfgId, 1, CfgField::Schedule); UpdateUI(); }); MoveText::getInstance()->LackResText(m_RootWidget, &lackData); } }); auto level = dataRow.GetValue(CfgField::Level)->asInt(); auto layout_Start = layout_Item->getChildByName<Layout*>("Start"); if (layout_Start != nullptr) { for (auto i = 1; i <= level; i++) { auto startName = StringUtils::format("Start_%d", i - 1); auto imgStart = layout_Start->getChildByName<ImageView*>(startName); if (imgStart != nullptr) imgStart->setVisible(true); } } viv.clear(); auto vmim = dataRow.GetValue(CfgField::MaterialID_M)->asIntMultiKeyMap(); CfgData::getInstance()->VMIMKToVIV_Sort(&vmim, &viv); for (auto i = 0; i < (viv.size() > 3 ? 3 : viv.size()); i++) { auto textName = StringUtils::format("Text_NameNum%d",i); auto text_NameNum = layout_Item->getChildByName<Text*>(textName); langId = CfgData::getInstance()->GetValue(viv[i].first, CfgField::Name)->asInt(); langText = MultiLanguage::getInstance()->GetText(langId); text_NameNum->setString(StringUtils::format("%s x%d", langText.c_str(), viv[i].second.asInt())); if(!UIUtils::getInstance()->isStuffEnough(viv[i].first, viv[i].second.asInt())) { // 数量不足,置灰 text_NameNum->setColor(Color3B(128, 128, 128)); } } auto btn_Explain = layout_Item->getChildByName<Button*>("Btn_Explain"); btn_Explain->addClickEventListener([=](Ref* sender) { CfgDataRow dataRow(cfgId); auto langId = dataRow.GetValue(CfgField::Details)->asInt(); auto langText = MultiLanguage::getInstance()->GetText(langId); TextExplainNode::getInstance()->UpdateText(m_RootWidget, &langText); }); } lView_List->refreshView(); }
void ArrayPerfTest::generateTestFunctions() { auto createArray = [this](){ __Array* ret = Array::create(); for( int i=0; i<quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(i); ret->addObject(node); } return ret; }; TestFunction testFunctions[] = { { "addObject", [=](){ __Array* nodeVector = Array::create(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->addObject(Node::create()); CC_PROFILER_STOP(this->profilerName()); } } , { "insertObject", [=](){ __Array* nodeVector = Array::create(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->insertObject(Node::create(), 0); CC_PROFILER_STOP(this->profilerName()); } } , { "setObject", [=](){ __Array* nodeVector = createArray(); srand((unsigned)time(nullptr)); ssize_t index = rand() % quantityOfNodes; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->setObject(Node::create(), index); CC_PROFILER_STOP(this->profilerName()); } } , { "getIndexOfObject", [=](){ __Array* nodeVector = createArray(); Ref* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); ssize_t index = 0; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) index = nodeVector->getIndexOfObject(objToGet); CC_PROFILER_STOP(this->profilerName()); // Uses `index` to avoids `getIndex` invoking was optimized in release mode if (index == quantityOfNodes/3) { nodeVector->removeAllObjects(); } } } , { "getObjectAtIndex", [=](){ __Array* nodeVector = createArray(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->getObjectAtIndex(quantityOfNodes/3); CC_PROFILER_STOP(this->profilerName()); } } , { "containsObject", [=](){ __Array* nodeVector = createArray(); Ref* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->containsObject(objToGet); CC_PROFILER_STOP(this->profilerName()); } } , { "removeObject", [=](){ __Array* nodeVector = createArray(); Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); for (int i = 0; i < quantityOfNodes; ++i) { nodes[i] = static_cast<Node*>(nodeVector->getObjectAtIndex(i)); } CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->removeObject(nodes[i]); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); free(nodes); } } , { "removeObjectAtIndex", [=](){ __Array* nodeVector = createArray(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->removeObjectAtIndex(0); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); } } , { "removeAllObjects", [=](){ __Array* nodeVector = createArray(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->removeAllObjects(); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); } } , { "swap by index", [=](){ __Array* nodeVector = createArray(); int swapIndex1 = quantityOfNodes / 3; int swapIndex2 = quantityOfNodes / 3 * 2; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->swap(swapIndex1, swapIndex2); CC_PROFILER_STOP(this->profilerName()); } } , { "swap by object", [=](){ __Array* nodeVector = createArray(); Ref* swapNode1 = nodeVector->getObjectAtIndex(quantityOfNodes / 3); Ref* swapNode2 = nodeVector->getObjectAtIndex(quantityOfNodes / 3 * 2); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->exchangeObject(swapNode1, swapNode2); CC_PROFILER_STOP(this->profilerName()); } } , { "reverseObjects", [=](){ __Array* nodeVector = createArray(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector->reverseObjects(); CC_PROFILER_STOP(this->profilerName()); } } , { "CCARRAY_FOREACH", [=](){ __Array* nodeVector = createArray(); Ref* obj; CC_PROFILER_START(this->profilerName()); CCARRAY_FOREACH(nodeVector, obj) { static_cast<Node*>(obj)->setTag(111); } CC_PROFILER_STOP(this->profilerName()); } } ,
void TileBoard::addTileAt(TileType type, int row, int column) { auto tile = GameTile::create(type, Point(getTileColumnPosition(column), getTileRowPosition(row)), row + 1, column + 1); tile->setTag(tileTagFor(row, column)); addChild(tile); }
void LevelTwo::createFlames(float dt) { for (int i = 0; i < 9; i++) { auto spritecache = SpriteFrameCache::getInstance(); spritecache->addSpriteFramesWithFile("GameScreen/fireList.plist"); cocos2d::SpriteFrame* spriteFrame = spritecache->getSpriteFrameByName("fire1.png"); cocos2d::Vector<cocos2d::Sprite *> m_aiSprites; cocos2d::Vector<cocos2d::SpriteFrame*> m_animFrames; for (int j = 1; j < 27; j++) { // Get a SpriteFrame using a name from the spritesheet .plist file. m_animFrames.pushBack(spritecache->getSpriteFrameByName("fire" + std::to_string(j) + ".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(2.0f); sprite->runAction(animate); auto fireBody = PhysicsBody::createBox(sprite->getContentSize(), PhysicsMaterial(0, 0, 0)); if (i == 0) { sprite->setPosition(Vec2(600, 420)); sprite->setTag(21); //fireBody->setCollisionBitmask(0x000101); //sprite->setPhysicsBody(fireBody); } else if (i == 1) { sprite->setPosition(Vec2(770, 420)); sprite->setTag(22); //fireBody->setCollisionBitmask(0x000201); //sprite->setPhysicsBody(fireBody); } else if (i == 2) { sprite->setPosition(Vec2(940, 420)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 3) { sprite->setPosition(Vec2(600, -20)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 4) { sprite->setPosition(Vec2(940, -20)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 5) { sprite->setPosition(Vec2(100, 260)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 6) { sprite->setPosition(Vec2(130, 130)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 7) { sprite->setPosition(Vec2(100, -20)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } else if (i == 8) { sprite->setPosition(Vec2(200, -20)); sprite->setTag(23); //fireBody->setCollisionBitmask(0x000301); //sprite->setPhysicsBody(fireBody); } this->addChild(sprite, 10); m_aiSprites.pushBack(sprite); if (dt == 5) { sprite->removeFromPhysicsWorld(); } for (int i = 0; i < m_aiSprites.size(); i++) { if (player->boundingBox().intersectsRect(sprite->boundingBox())) { playerOneDead = true; } if (player2->boundingBox().intersectsRect(sprite->boundingBox())) { playerTwoDead = true; } } //m_aiSprites.clear(); } }
bool Ranking::init() { if (!Layer::init()) { return false; } _totalLabels = 2; Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto backgroundWin = Sprite::create(ImageManager::getImage("background-win"), visibleRect); backgroundWin->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); backgroundWin->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(backgroundWin); buttonsLayer = Layer::create(); buttonsLayer->setContentSize(visibleRect.size); buttonsLayer->setPosition(0, 0); auto buttonBack = SpriteButton::create(ImageManager::getImage("back"), 0.30f, CC_CALLBACK_1(Ranking::returnHome, this)); buttonBack->setTag(static_cast<int>(SceneType::MAIN)); buttonBack->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonBack = ScreenSizeManager::getScreenPositionFromPercentage(5, 5); positionButtonBack.x += buttonBack->getBoundingBox().size.width / 2; positionButtonBack.y += buttonBack->getBoundingBox().size.height / 2; buttonBack->setPosition(positionButtonBack); buttonsLayer->addChild(buttonBack); auto buttonAbout = SpriteButton::create(ImageManager::getImage("info"), 0.30f, CC_CALLBACK_1(Ranking::openInfo, this)); buttonAbout->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonAbout = ScreenSizeManager::getScreenPositionFromPercentage(95, 5); positionButtonAbout.x -= buttonAbout->getBoundingBox().size.width / 2; positionButtonAbout.y += buttonAbout->getBoundingBox().size.height / 2; buttonAbout->setPosition(positionButtonAbout); buttonsLayer->addChild(buttonAbout); auto buttonSFXSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Ranking::switchSoundSettings, this)); buttonSFXSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSFXSettings = buttonAbout->getPosition(); positionButtonSFXSettings.x -= ScreenSizeManager::getWidthFromPercentage(5); positionButtonSFXSettings.x -= buttonSFXSettings->getBoundingBox().size.width; buttonSFXSettings->setPosition(positionButtonSFXSettings); buttonsLayer->addChild(buttonSFXSettings); this->addChild(buttonsLayer); _labelLoading = Label::createWithTTF(LanguageManager::getLocalizedText("Ranking", "loading"), MainRegularFont, 100); _labelLoading->setAnchorPoint(Point::ANCHOR_MIDDLE); _labelLoading->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); _labelLoading->setTextColor(IkasPurple); this->addChild(_labelLoading); /* TableView */ _tableViewRanking = TableView::create(this, Size(ScreenSizeManager::getWidthFromPercentage(TableViewWidthPercentage), ScreenSizeManager::getHeightFromPercentage(TableViewHeightPercentage))); _tableViewRanking->setColor(Color3B(Color3B(200, 200, 200))); Vec2 positionTablewView = ScreenSizeManager::getScreenPositionFromPercentage(TableViewXPositionPercentage, TableViewYPositionPercentage); positionTablewView.x -= _tableViewRanking->getBoundingBox().size.width/2; positionTablewView.y -= _tableViewRanking->getBoundingBox().size.height/2; _tableViewRanking->setPosition(positionTablewView); this->addChild(_tableViewRanking); auto labelUserTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Ranking", "player"), MainRegularFont, 80); labelUserTitle->setAnchorPoint(Point::ANCHOR_MIDDLE); labelUserTitle->setPosition(Vec2(_tableViewRanking->getPositionX() + (_tableViewRanking->getBoundingBox().size.width) * 0.25f, _tableViewRanking->getPositionY() + (_tableViewRanking->getBoundingBox().size.height) * 1.1f)); labelUserTitle->setTextColor(IkasPurpleLight); this->addChild(labelUserTitle); auto labelPointsTitle = Label::createWithTTF(LanguageManager::getLocalizedText("Ranking", "points"), MainRegularFont, 80); labelPointsTitle->setAnchorPoint(Point::ANCHOR_MIDDLE); labelPointsTitle->setPosition(Vec2(_tableViewRanking->getPositionX() + (_tableViewRanking->getBoundingBox().size.width) * 0.75f, _tableViewRanking->getPositionY() + (_tableViewRanking->getBoundingBox().size.height) * 1.1f)); labelPointsTitle->setTextColor(IkasPurpleLight); this->addChild(labelPointsTitle); _api = new IkasAPI(); _api->checkForLatestRankingData(CC_CALLBACK_2(Ranking::successRankingDataDownloaded, this), CC_CALLBACK_1(Ranking::errorDataDownloaded, this)); return true; }
void HtmlReader::readDocument(ZLInputStream &stream) { if (!stream.open()) { return; } startDocumentHandler(); ParseState state = PS_TEXT; SpecialType state_special = ST_UNKNOWN; std::string currentString; std::string attributeValueString; std::string specialString; int quotationCounter = 0; HtmlTag currentTag; char endOfComment[2] = "\0"; const size_t BUFSIZE = 2048; char *buffer = new char[BUFSIZE]; size_t length; size_t offset = 0; do { length = stream.read(buffer, BUFSIZE); char *start = buffer; char *endOfBuffer = buffer + length; for (char *ptr = buffer; ptr < endOfBuffer; ++ptr) { switch (state) { case PS_TEXT: if (*ptr == '<') { if (!characterDataHandler(start, ptr - start, true)) { goto endOfProcessing; } start = ptr + 1; state = PS_TAGSTART; currentTag.Offset = offset + (ptr - buffer); } if (*ptr == '&') { if (!characterDataHandler(start, ptr - start, true)) { goto endOfProcessing; } start = ptr + 1; state = PS_SPECIAL; state_special = ST_UNKNOWN; } break; case PS_SPECIAL: case PS_SPECIAL_IN_ATTRIBUTEVALUE: if (state_special == ST_UNKNOWN) { if (*ptr == '#') { state_special = ST_NUM; } else if (isalpha(*ptr)) { state_special = ST_NAME; } else { start = ptr; state = (state == PS_SPECIAL) ? PS_TEXT : PS_ATTRIBUTEVALUE; } } else if (state_special == ST_NUM) { if (*ptr == 'x') { state_special = ST_HEX; } else if (isdigit(*ptr)) { state_special = ST_DEC; } else { start = ptr; state = (state == PS_SPECIAL) ? PS_TEXT : PS_ATTRIBUTEVALUE; } } else { if (*ptr == ';') { specialString.append(start, ptr - start); int number = specialSymbolNumber(state_special, specialString); if ((128 <= number) && (number <= 159)) { char ch = number; if (state == PS_SPECIAL) { characterDataHandler(&ch, 1, true); } else { myConverter->convert(attributeValueString, &ch, &ch + 1); } } else if (number != 0) { char buffer[4]; int len = ZLUnicodeUtil::ucs4ToUtf8(buffer, number); if (state == PS_SPECIAL) { characterDataHandler(buffer, len, false); } else { attributeValueString.append(buffer, len); } } else { specialString = "&" + specialString + ";"; if (state == PS_SPECIAL) { characterDataHandler(specialString.c_str(), specialString.length(), false); } else { attributeValueString += specialString; } } specialString.erase(); start = ptr + 1; state = (state == PS_SPECIAL) ? PS_TEXT : PS_ATTRIBUTEVALUE; } else if (!allowSymbol(state_special, *ptr)) { start = ptr; state = (state == PS_SPECIAL) ? PS_TEXT : PS_ATTRIBUTEVALUE; } } break; case PS_TAGSTART: state = (*ptr == '!') ? PS_COMMENT : PS_TAGNAME; break; case PS_COMMENT: if ((endOfComment[0] == '\0') && (*ptr != '-')) { state = PS_TAGNAME; } else if ((endOfComment[0] == '-') && (endOfComment[1] == '-') && (*ptr == '>')) { start = ptr + 1; state = PS_TEXT; endOfComment[0] = '\0'; endOfComment[1] = '\0'; } else { endOfComment[0] = endOfComment[1]; endOfComment[1] = *ptr; } break; case PS_TAGNAME: if ((*ptr == '>') || isspace((unsigned char)*ptr)) { currentString.append(start, ptr - start); start = ptr + 1; setTag(currentTag, currentString); currentString.erase(); if (currentTag.Name == "") { state = (*ptr == '>') ? PS_TEXT : PS_SKIPTAG; } else { if (*ptr == '>') { if (!tagHandler(currentTag)) { goto endOfProcessing; } state = PS_TEXT; } else { state = PS_ATTRIBUTENAME; } } } break; case PS_ATTRIBUTENAME: if ((*ptr == '>') || (*ptr == '=') || isspace((unsigned char)*ptr)) { if ((ptr != start) || !currentString.empty()) { currentString.append(start, ptr - start); for (unsigned int i = 0; i < currentString.length(); ++i) { currentString[i] = toupper(currentString[i]); } currentTag.addAttribute(currentString); currentString.erase(); } start = ptr + 1; if (*ptr == '>') { if (!tagHandler(currentTag)) { goto endOfProcessing; } state = PS_TEXT; } else { state = (*ptr == '=') ? PS_ATTRIBUTEVALUE : PS_ATTRIBUTENAME; } } break; case PS_ATTRIBUTEVALUE: if (*ptr == '"') { if (((ptr == start) && currentString.empty()) || (quotationCounter > 0)) { ++quotationCounter; } } else if (*ptr == '&') { currentString.append(start, ptr - start); start = ptr + 1; appendString(attributeValueString, currentString); state = PS_SPECIAL_IN_ATTRIBUTEVALUE; state_special = ST_UNKNOWN; } else if ((quotationCounter != 1) && ((*ptr == '>') || isspace((unsigned char)*ptr))) { if ((ptr != start) || !currentString.empty()) { currentString.append(start, ptr - start); appendString(attributeValueString, currentString); if (attributeValueString[0] == '"') { attributeValueString = attributeValueString.substr(1, attributeValueString.length() - 2); } currentTag.setLastAttributeValue(attributeValueString); attributeValueString.erase(); quotationCounter = 0; } start = ptr + 1; if (*ptr == '>') { if (!tagHandler(currentTag)) { goto endOfProcessing; } state = PS_TEXT; } else { state = PS_ATTRIBUTENAME; } } break; case PS_SKIPTAG: if (*ptr == '>') { start = ptr + 1; state = PS_TEXT; } break; } } if (start != endOfBuffer) { switch (state) { case PS_TEXT: if (!characterDataHandler(start, endOfBuffer - start, true)) { goto endOfProcessing; } break; case PS_TAGNAME: case PS_ATTRIBUTENAME: case PS_ATTRIBUTEVALUE: currentString.append(start, endOfBuffer - start); break; case PS_SPECIAL: case PS_SPECIAL_IN_ATTRIBUTEVALUE: specialString.append(start, endOfBuffer - start); break; case PS_TAGSTART: case PS_SKIPTAG: case PS_COMMENT: break; } } offset += length; } while (length == BUFSIZE); endOfProcessing: delete[] buffer; endDocumentHandler(); stream.close(); }
void HUD::fadeBlackTo(int opacity, float duration) { auto fade = CCFadeTo::create(duration, opacity); fade->setTag(fadeTag); black->stopActionByTag(fadeTag); black->runAction(fade); }
void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) { //srandom(0); subtestNumber = asubtest; _subTest = new SubTest; _subTest->initWithSubTest(asubtest, this); auto s = Director::getInstance()->getWinSize(); lastRenderedCount = 0; quantityNodes = 0; MenuItemFont::setFontSize(65); auto decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(SpriteMainScene::onDecrease, this)); decrease->setColor(Color3B(0,200,20)); auto increase = MenuItemFont::create(" + ", CC_CALLBACK_1(SpriteMainScene::onIncrease, this)); increase->setColor(Color3B(0,200,20)); auto menu = Menu::create(decrease, increase, NULL); menu->alignItemsHorizontally(); menu->setPosition(Vec2(s.width/2, s.height-65)); addChild(menu, 1); auto infoLabel = Label::createWithTTF("0 nodes", "fonts/Marker Felt.ttf", 30); infoLabel->setColor(Color3B(0,200,20)); infoLabel->setPosition(Vec2(s.width/2, s.height-90)); addChild(infoLabel, 1, kTagInfoLayer); // add menu auto menuLayer = new SpriteMenuLayer(true, TEST_COUNT, SpriteMainScene::_s_nSpriteCurCase); addChild(menuLayer, 1, kTagMenuLayer); menuLayer->release(); /** * auto test menu */ auto menuAutoTest = Menu::create(); menuAutoTest->setPosition( Vec2::ZERO ); MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(24); MenuItemFont* autoTestItem = NULL; if (SpriteMainScene::_s_autoTest) { autoTestItem = MenuItemFont::create("Auto Test On",CC_CALLBACK_1(SpriteMainScene::onAutoTest, this)); } else { autoTestItem = MenuItemFont::create("Auto Test Off",CC_CALLBACK_1(SpriteMainScene::onAutoTest, this)); } autoTestItem->setTag(1); autoTestItem->setPosition(Vec2( s.width - 90, s.height / 2)); menuAutoTest->addChild(autoTestItem); addChild( menuAutoTest, 3, kTagAutoTestMenu ); // Sub Tests MenuItemFont::setFontSize(28); auto subMenu = Menu::create(); for (int i = 1; i <= 13; ++i) { char str[10] = {0}; sprintf(str, "%d ", i); auto itemFont = MenuItemFont::create(str, CC_CALLBACK_1(SpriteMainScene::testNCallback, this)); itemFont->setTag(i); subMenu->addChild(itemFont, 10); if( i<= 4) itemFont->setColor(Color3B(200,20,20)); else if(i <= 8) itemFont->setColor(Color3B(0,200,20)); else if( i<=12) itemFont->setColor(Color3B(0,20,200)); else itemFont->setColor(Color3B::GRAY); } subMenu->alignItemsHorizontally(); subMenu->setPosition(Vec2(s.width/2, 80)); addChild(subMenu, 2); // add title label auto label = Label::createWithTTF(title(), "fonts/arial.ttf", 32); addChild(label, 1); label->setPosition(Vec2(s.width/2, s.height-50)); // subtitle std::string strSubtitle = subtitle(); if( ! strSubtitle.empty() ) { auto l = Label::createWithTTF(strSubtitle.c_str(), "fonts/Thonburi.ttf", 16); addChild(l, 9999); l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 60) ); } while(quantityNodes < nNodes) onIncrease(this); }
void smallStone::doAnimate(stoneAnimateType type) { switch (type) { case smallStone::stoneAnimateType::ani_shake: { const int shake_tag = 1111; if (this->getActionByTag(shake_tag)) { break; } const int MAX_OFFSET = 20; int offset = MAX_OFFSET; float time = 0.08f; auto size = this->getContentSize(); auto scaleX = (size.width + offset) / size.width; auto scaleY = (size.height - offset) / size.height; auto sq1 = Sequence::create(MoveBy::create(time, Point(0, 0- offset)), ScaleBy::create(time, scaleX, scaleY), nullptr); time = 0.09; auto sq2 = Sequence::create(MoveBy::create(time/2, Point(0, offset)), ScaleTo::create(time / 2, 1, 1), nullptr); offset = MAX_OFFSET/2; time = 0.10; scaleX = (size.width + offset) / size.width; scaleY = (size.height - offset) / size.height; auto sq3 = Sequence::create(MoveBy::create(time, Point(0, - offset)), ScaleBy::create(time, scaleX, scaleY), nullptr); time = 0.11; auto sq4 = Sequence::create(MoveBy::create(time / 2, Point(0, offset)), ScaleTo::create(time / 2, 1, 1), nullptr); auto sq = Sequence::create(sq1, sq2, sq3, sq4, nullptr); sq->setTag(shake_tag); this->runAction(sq); } break; case smallStone::stoneAnimateType::ani_cute: { const int cute_tag = 1112; if (this->getActionByTag(cute_tag)) { break; } Vector<SpriteFrame*> frames; for (int i = 1; i < 3; i++) { SpriteFrame * frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteNormal[_imgIndex][i]); frames.pushBack(frame); } Animation * animation = Animation::createWithSpriteFrames(frames, 0.2f); Animate * ani = Animate::create(animation); std::function<void()> call = [=](){ SpriteFrame * frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteNormal[_imgIndex][0]); this->setSpriteFrame(frame); }; Sequence * sq = Sequence::create(Repeat::create(ani, 3), CCCallFunc::create(call), nullptr); sq->setTag(cute_tag); this->runAction(sq); } break; case smallStone::stoneAnimateType::ani_whiteEye: { const int whiteEye_tag = 1113; if (this->getActionByTag(whiteEye_tag)) { break; } SpriteFrame * frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteNormal[_imgIndex][4]); this->setSpriteFrame(frame); } break; default: break; } }
bool WelcomeLayer::init() { if (!Layer::init()) { return false; } auto visibileSize = Director::getInstance()->getVisibleSize(); auto atlasLoader = AtlasLoader::getInstance(); //获取系统时间 time_t t = time(NULL); tm* lt = localtime(&t); int hour = lt->tm_hour; Sprite *bg = nullptr; //根据时间获取背景 if (hour >= 6 && hour <= 17) { bg = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("bg_day")); } else { bg = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("bg_night")); } bg->setPosition(visibileSize / 2); this->addChild(bg); //添加陆地 this->land1 = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("land")); this->land2 = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("land")); auto landSize = land1->getContentSize(); this->land1->setPosition(visibileSize.width / 2, landSize.height / 2); this->land2->setPosition(visibileSize.width / 2 + landSize.width - 1, landSize.height / 2); this->addChild(this->land1); this->addChild(this->land2); this->schedule(schedule_selector(WelcomeLayer::scroolLand), 0.01f); //添加标题 auto title = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("title")); title->setPosition(visibileSize.width / 2, visibileSize.height / 4 * 3); title->setTag(TITLE_TAG); this->addChild(title); //版权描述 auto copyRight = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("brand_copyright")); copyRight->setPosition(visibileSize.width / 2, visibileSize.height / 6); copyRight->setTag(COPY_RIGHT_TAG); this->addChild(copyRight); //开始按钮 auto startButton = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("button_play")); auto activeStartButton = Sprite::createWithSpriteFrame(atlasLoader->getSpriteFrameByName("button_play")); activeStartButton->setPositionY(5); auto menuItem = MenuItemSprite::create(startButton, activeStartButton, NULL, CC_CALLBACK_1(WelcomeLayer::menuCallback, this)); auto menu = Menu::create(menuItem, NULL); menu->setPosition(visibileSize.width / 2, visibileSize.height / 3 + 30); menu->setTag(MENU_TAG); this->addChild(menu); //添加小鸟 this->bird = BirdSprite::getInstance(); this->bird->createBird(); this->bird->setTag(BIRD_SPRITE_TAG); this->bird->setPosition(visibileSize.width / 2, visibileSize.height / 2 + 30); this->bird->idle(); this->addChild(bird); return true; }
bool Game1Scene::init(){ if (!LayerColor::initWithColor(GAME1_COLOR_APPCOLOR)) { return false; } else{ //初始化游戏UI auto gameUI = Game1UI::createLayer(); gameUI->setTag(999); this->addChild(gameUI); //初始化游戏背景 Size gameBoardSize = Size(GAME1_BLOCK_WIDTH * GAME1_COLS + GAME1_PADDING * (GAME1_COLS + 1), GAME1_BLOCK_HEIGHT * GAME1_ROWS + GAME1_PADDING * (GAME1_ROWS + 1)); gameBoard = LayerColor::create(GAME1_COLOR_BOARDCOLOR, gameBoardSize.width, gameBoardSize.height); Point gameBoardPoint = Point(70,(GAME1_WIN_SIZE_HEIGHT - gameBoardSize.height) / 2); gameBoard->setPosition(gameBoardPoint); this->addChild(gameBoard); //初始化Block for (int r = 0; r < GAME1_ROWS; r++) { for (int c = 0; c < GAME1_COLS; c++) { LayerColor * block = LayerColor::create(GAME1_COLOR_BLOCKCOLOR, GAME1_BLOCK_WIDTH, GAME1_BLOCK_HEIGHT); block->setPosition(c * (GAME1_BLOCK_WIDTH + GAME1_PADDING) + GAME1_PADDING, r * (GAME1_BLOCK_HEIGHT + GAME1_PADDING) + GAME1_PADDING); gameBoard->addChild(block); } } //初始化map for (int r = 0; r < GAME1_ROWS; r++) { for (int c = 0; c < GAME1_COLS; c++) { map[r][c] = -1; } } //初始化第一块Tile createOneTile(); //操作监控 auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [&](Touch * touch, Event * event){ //触摸开始时,记录下位置,作为后续触摸距离超过10像素的比较初始点 this->touchStartPoint = touch->getLocationInView(); log("touch began"); //设置标志位,表示新一轮开始,并且还没进行处理 this->touchIsEffective = false; return true; }; listener->onTouchMoved = [&](Touch * touch, Event * event){ //如果还没进行处理,才进行后续逻辑判断 if (!this->touchIsEffective) { //判断移动位置是否超过10像素,如果超过则证明当次移动已经有效,否则该移动无效 Vec2 touchCurrentPoint = touch->getLocationInView(); if (abs(touchCurrentPoint.x - this->touchStartPoint.x) >= GAME1_TOUCH_EFFECTIVE_DIS || abs(touchCurrentPoint.y - this->touchStartPoint.y) >= GAME1_TOUCH_EFFECTIVE_DIS) { this->touchIsEffective = true; log("touch is effect"); } //如果移动有效 if (this->touchIsEffective) { //判断移动的方向 if(touchCurrentPoint.x - this->touchStartPoint.x >= GAME1_TOUCH_EFFECTIVE_DIS){ this->currentDirection = RIGHT; //log("RIGHT"); } else if(this->touchStartPoint.x - touchCurrentPoint.x >= GAME1_TOUCH_EFFECTIVE_DIS){ this->currentDirection = LEFT; //log("LEFT"); } else if(touchCurrentPoint.y - this->touchStartPoint.y >= GAME1_TOUCH_EFFECTIVE_DIS){ this->currentDirection = DOWN; //log("DOWN"); } else if(this->touchStartPoint.y - touchCurrentPoint.y >= GAME1_TOUCH_EFFECTIVE_DIS){ this->currentDirection = UP; //log("UP"); } else{ this->currentDirection = NODIR; //log("NODIR"); //exit(1); } //进行一轮游戏逻辑的操作,该轮后续的滑动不再处理 this->oneRound(); } } }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; } }
bool MainMenu::init() { if (!Layer::init()) { return false; } log("MainMenu init"); //(0.5, 1 - 0.618) auto position = Vec2(origin.x + visible_size.width / 2 , origin.y + visible_size.height * (1 - 0.618)); // scene turn to option function auto create_menu_turn_to_option = [](string name) { return MenuItemFont::create(get_UTF8_string(name), [name](Ref *sender) { auto next_scene = Option::createScene(name); auto Transition_scene = TransitionCrossFade::create(SCENE_TURN_TRANSITION_TIME, next_scene); Director::getInstance()->replaceScene(Transition_scene); }); }; //main menu auto menu_start = MenuItemFont::create(get_UTF8_string("start"), [=](Ref *sender) { log("hit start"); auto next_scene = GameMenu::createScene(); auto Transition_scene = TransitionCrossFade::create(SCENE_TURN_TRANSITION_TIME, next_scene); Director::getInstance()->replaceScene(Transition_scene); }); auto menu_option_setting = create_menu_turn_to_option("setting"); auto menu_option_help = create_menu_turn_to_option("help"); auto menu_option_about = create_menu_turn_to_option("about"); auto menu_option_feedback = create_menu_turn_to_option("feedback"); auto menu_exit = MenuItemFont::create(get_UTF8_string("exit"), [=](Ref *sender) { Director::getInstance()->end(); }); //add into a vector vector<MenuItem *> vector_menu; vector_menu.push_back(menu_start); vector_menu.push_back(menu_option_setting); vector_menu.push_back(menu_option_help); vector_menu.push_back(menu_option_about); vector_menu.push_back(menu_option_feedback); vector_menu.push_back(menu_exit); //max content width auto menu_item_width = 0.0f; for (auto m : vector_menu) { menu_item_width = max(menu_item_width, m->getContentSize().width); } //get action of turn menu auto ac_rotate_to_n90 = RotateTo::create(MAIN_MENU_TURN_TIME, Vec3(0, -90, 0)); auto ac_rotate_to_90 = RotateTo::create(MAIN_MENU_TURN_TIME, Vec3(0, 90, 0)); auto ac_rotate_to_0 = RotateTo::create(MAIN_MENU_TURN_TIME, Vec3(0, 0, 0)); auto ac_fade_out = FadeOut::create(MAIN_MENU_TURN_TIME); auto ac_fade_in = FadeIn::create(MAIN_MENU_TURN_TIME); auto ac_move_to_mid = MoveTo::create(MAIN_MENU_TURN_TIME, position); auto ac_move_to_left = MoveTo::create(MAIN_MENU_TURN_TIME, position - Vec2(menu_item_width / 2, 0)); auto ac_move_to_right = MoveTo::create(MAIN_MENU_TURN_TIME, position + Vec2(menu_item_width / 2, 0)); auto ac_turn_right = Sequence::create(Spawn::create(ac_rotate_to_90, ac_move_to_right, ac_fade_out, NULL), CallFuncN::create([](Ref *sender) { ((Node *)sender)->setVisible(false); log("right"); }), NULL); auto ac_turn_mid = Sequence::create(CallFuncN::create([](Ref *sender) { ((Node *)sender)->setVisible(true); log("mid"); }), Spawn::create(ac_rotate_to_0, ac_move_to_mid, ac_fade_in, NULL), NULL); auto ac_turn_left = Sequence::create(Spawn::create(ac_rotate_to_n90, ac_move_to_left, ac_fade_out, NULL), CallFuncN::create([](Ref *sender) { ((Node *)sender)->setVisible(false); log("left"); }), NULL); ac_turn_right->retain(); ac_turn_mid->retain(); ac_turn_left->retain(); //if ac_turn_mid has not run, set tag = 1 ac_turn_mid->setTag(1); //add turn menu auto menu_turn_left = MenuItemFont::create(" < ", [=](Ref *sender) { //if ac_turn_mid is runing, tag = 0; isDone = flase if (ac_turn_mid->isDone() + ac_turn_mid->getTag() == 0) { return; } //if ac_turn_mid has been run, set tag = 0 ac_turn_mid->setTag(0); //run action vector_menu[menu_id]->runAction(ac_turn_left); //next menu id menu_id = (menu_id + 1) % vector_menu.size(); //init menu item vector_menu[menu_id]->stopAllActions(); vector_menu[menu_id]->setPosition(position + Vec2(menu_item_width / 2, 0)); vector_menu[menu_id]->setRotation3D(Vec3(0, 90, 0)); vector_menu[menu_id]->setOpacity(100); vector_menu[menu_id]->setVisible(false); //run action vector_menu[menu_id]->runAction(ac_turn_mid); }); auto menu_turn_right = MenuItemFont::create(" > ", [=](Ref *sender) { if (ac_turn_mid->isDone() + ac_turn_mid->getTag() == 0) { return; } //if ac_turn_mid has been run, set tag = 0 ac_turn_mid->setTag(0); //run action vector_menu[menu_id]->runAction(ac_turn_right); //next menu id menu_id = (menu_id - 1 + vector_menu.size()) % vector_menu.size(); //init menu item vector_menu[menu_id]->stopAllActions(); vector_menu[menu_id]->setPosition(position - Vec2(menu_item_width / 2, 0)); vector_menu[menu_id]->setRotation3D(Vec3(0, -90, 0)); vector_menu[menu_id]->setOpacity(100); vector_menu[menu_id]->setVisible(false); //run action vector_menu[menu_id]->runAction(ac_turn_mid); }); //create menu auto menu = Menu::create(menu_turn_left, menu_turn_right, NULL); menu->setPosition(Vec2::ZERO); menu->setAnchorPoint(Vec2::ZERO); menu_turn_left->setPosition(position - Vec2(menu_item_width / 2 + menu_turn_left->getContentSize().width / 2, 0)); menu_turn_right->setPosition(position + Vec2(menu_item_width / 2 + menu_turn_right->getContentSize().width / 2, 0)); this->addChild(menu); //init all menu itme for (auto m : vector_menu) { menu->addChild(m); m->setVisible(false); } menu_id = 0; //init menu item vector_menu[menu_id]->setPosition(position); vector_menu[menu_id]->setRotation3D(Vec3(0, 0, 0)); vector_menu[menu_id]->setOpacity(255); vector_menu[menu_id]->setVisible(true); return true; }
// 0~2のアニメーションを再生するメソッド(0通常、1上、2下) //void型のPlayer::playAnimation(int index)関数を作成 void Player::playAnimation(int index) { //もしも変数indexCheckと変数indexが等しかったら if (indexCheck == index) { //ここで関数の処理を終了する return; } // アニメーション用のタグを固定値で定義 const int ACTION_TAG = 999; // 好きな数 // 既にアニメーションが動いていたら止める // アニメーションには全て999のタグが付いてるはずなので、重複しないように止める this->stopActionByTag(ACTION_TAG); // cocos2d::Size型のframeSize変数で表示するかわずたんのスプライトのサイズを指定? //Size(frameSize.width, frameSize.height)にそれぞれ16.0を代入している。型はfloat auto frameSize = cocos2d::Size(16.0, 24.0); //? //スプライトのX座標0、Y座標0(左上)から、16x16を切り出す? //Rectはx,y,width,heightの4つをとれる。矩形という意味 this->setTextureRect(cocos2d::Rect(0, 0, frameSize.width, frameSize.height)); //SpriteFrame*というテンプレートでframesという配列を宣言 Vector<SpriteFrame*> frames; //変数iを宣言、0で初期化しiがFRAME_COUNT未満である時、変数iに1を加算し{}内の処理を行いループ //iがFRAME_COUNT未満でなくなった時にループを抜ける for (int i = 0; i < FRAME_COUNT; ++i) { // indexの値によってy座標を変える //cocos2d::SpriteFrame型のポイント変数frameを宣言 //画像kawaz_shooting.pngを読み、frameSize.widthにiをかけ2コマアニメーションのループ //indexに16(frameSize.heightの値)をかけ、アニメーションを切り替え //frameSize.widthとframeSize.heightで表示する画像の大きさを指定? auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width * i, index * frameSize.height, frameSize.width, frameSize.height)); //配列framesの終わりにframeの値を挿入する frames.pushBack(frame); } auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width, index * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); if (index == 2) { frames.clear(); auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width, 2 * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); } else if (index == 3) { frames.clear(); auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width * 2, 2 * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); } else if (index == 4) { frames.clear(); auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(0, 3 * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); } else if (index == 5) { frames.clear(); auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width, 3 * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); } else if (index == 6) { frames.clear(); auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width * 2, 3 * frameSize.height, frameSize.width, frameSize.height)); frames.pushBack(frame); } else if (index == 7) { frames.clear(); for (int i = 0; i <= FRAME_COUNT; ++i) { auto frame = SpriteFrame::create("graphics/luk_sprite.png", cocos2d::Rect(frameSize.width * i, 96, frameSize.width, frameSize.height)); frames.pushBack(frame); } } //cocos2d::Animation型のポインタ変数animationを宣言 //配列framesを代入してるっぽいけどWithなんちゃらがよくわからない auto animation = Animation::createWithSpriteFrames(frames); if (index == 0) { animation->setDelayPerUnit(0.2); } else if (index == 7) { animation->setDelayPerUnit(0.3); } else { animation->setDelayPerUnit(0.1); } if (index != 7) { //cocos2d::RepeatForever型のポインタ変数animateを宣言 なんか闇っぽい //Animate::create(animation)でanimationで宣言された2コマアニメを生成してるとおもう //RepeatForeverは生成したアニメーションをを無限に繰り返す auto animate = RepeatForever::create(Animate::create(animation)); //ポインタ変数animateにACTION_TAGというタグを設定 animate->setTag(ACTION_TAG); //animateというアクションを走らせる this->runAction(animate); } else { auto clearAnimate = Animate::create(animation); clearAnimate->setTag(ACTION_TAG); this->runAction(clearAnimate); } //indexCheckにindexの値を代入する indexCheck = index; }
void TouchEventDispatchingPerfTest::generateTestFunctions() { TestFunction testFunctions[] = { { "OneByOne-scenegraph", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch* touch, Event* event){ return false; }; listener->onTouchMoved = [](Touch* touch, Event* event){}; listener->onTouchEnded = [](Touch* touch, Event* event){}; // Create new touchable nodes for (int i = 0; i < this->_quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(1000 + i); this->addChild(node); this->_nodes.push_back(node); dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , { "OneByOne-fixed", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch* touch, Event* event){ return false; }; listener->onTouchMoved = [](Touch* touch, Event* event){}; listener->onTouchEnded = [](Touch* touch, Event* event){}; for (int i = 0; i < this->_quantityOfNodes; ++i) { auto l = listener->clone(); this->_fixedPriorityListeners.push_back(l); dispatcher->addEventListenerWithFixedPriority(l, i+1); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , { "AllAtOnce-scenegraph", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){}; listener->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){}; listener->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){}; // Create new touchable nodes for (int i = 0; i < this->_quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(1000 + i); this->addChild(node); this->_nodes.push_back(node); dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , { "AllAtOnce-fixed", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){}; listener->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){}; listener->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){}; for (int i = 0; i < this->_quantityOfNodes; ++i) { auto l = listener->clone(); this->_fixedPriorityListeners.push_back(l); dispatcher->addEventListenerWithFixedPriority(l, i+1); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , { "TouchModeMix-scenegraph", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listenerOneByOne = EventListenerTouchOneByOne::create(); listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ return false; }; listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); listenerAllAtOnce->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){}; listenerAllAtOnce->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){}; listenerAllAtOnce->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){}; int i = 0; // Create new touchable nodes for (; i < this->_quantityOfNodes/2; ++i) { auto node = Node::create(); node->setTag(1000 + i); this->addChild(node); this->_nodes.push_back(node); dispatcher->addEventListenerWithSceneGraphPriority(listenerOneByOne->clone(), node); } for (; i < this->_quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(1000 + i); this->addChild(node); this->_nodes.push_back(node); dispatcher->addEventListenerWithSceneGraphPriority(listenerAllAtOnce->clone(), node); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , { "TouchModeMix-fixed", [=](){ auto dispatcher = Director::getInstance()->getEventDispatcher(); if (_quantityOfNodes != _lastRenderedCount) { auto listenerOneByOne = EventListenerTouchOneByOne::create(); listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ return false; }; listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); listenerAllAtOnce->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){}; listenerAllAtOnce->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){}; listenerAllAtOnce->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){}; int i = 0; for (; i < this->_quantityOfNodes/2; ++i) { auto l = listenerOneByOne->clone(); this->_fixedPriorityListeners.push_back(l); dispatcher->addEventListenerWithFixedPriority(l, i+1); } for (; i < this->_quantityOfNodes; ++i) { auto l = listenerAllAtOnce->clone(); this->_fixedPriorityListeners.push_back(l); dispatcher->addEventListenerWithFixedPriority(l, i+1); } _lastRenderedCount = _quantityOfNodes; } Size size = Director::getInstance()->getWinSize(); EventTouch touchEvent; touchEvent.setEventCode(EventTouch::EventCode::BEGAN); std::vector<Touch*> touches; for (int i = 0; i < 4; ++i) { Touch* touch = new Touch(); touch->autorelease(); touch->setTouchInfo(i, rand() % 200, rand() % 200); touches.push_back(touch); } touchEvent.setTouches(touches); CC_PROFILER_START(this->profilerName()); dispatcher->dispatchEvent(&touchEvent); CC_PROFILER_STOP(this->profilerName()); } } , }; for (const auto& func : testFunctions) { _testFunctions.push_back(func); } }
void TemplateVectorPerfTest::generateTestFunctions() { auto createVector = [this](){ Vector<Node*> ret; for( int i=0; i<quantityOfNodes; ++i) { auto node = Node::create(); node->setTag(i); ret.pushBack(node); } return ret; }; TestFunction testFunctions[] = { { "pushBack", [=](){ Vector<Node*> nodeVector; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.pushBack(Node::create()); CC_PROFILER_STOP(this->profilerName()); } } , { "insert", [=](){ Vector<Node*> nodeVector; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.insert(0, Node::create()); CC_PROFILER_STOP(this->profilerName()); } } , { "replace", [=](){ Vector<Node*> nodeVector = createVector(); srand((unsigned)time(nullptr)); ssize_t index = rand() % quantityOfNodes; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.replace(index, Node::create()); CC_PROFILER_STOP(this->profilerName()); } } , { "getIndex", [=](){ Vector<Node*> nodeVector = createVector(); Node* objToGet = nodeVector.at(quantityOfNodes/3); ssize_t index = 0; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) index = nodeVector.getIndex(objToGet); CC_PROFILER_STOP(this->profilerName()); // Uses `index` to avoids `getIndex` invoking was optimized in release mode if (index == quantityOfNodes/3) { nodeVector.clear(); } } } , { "find", [=](){ Vector<Node*> nodeVector = createVector(); Node* objToGet = nodeVector.at(quantityOfNodes/3); Vector<Node*>::iterator iter; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) iter = nodeVector.find(objToGet); CC_PROFILER_STOP(this->profilerName()); // Uses `iter` to avoids `find` invoking was optimized in release mode if (*iter == objToGet) { nodeVector.clear(); } } } , { "at", [=](){ Vector<Node*> nodeVector = createVector(); Node* objToGet = nullptr; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) objToGet = nodeVector.at(quantityOfNodes/3); CC_PROFILER_STOP(this->profilerName()); // Uses `objToGet` to avoids `at` invoking was optimized in release mode if (nodeVector.getIndex(objToGet) == quantityOfNodes/3) { nodeVector.clear(); } } } , { "contains", [=](){ Vector<Node*> nodeVector = createVector(); Node* objToGet = nodeVector.at(quantityOfNodes/3); bool ret = false; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) ret = nodeVector.contains(objToGet); CC_PROFILER_STOP(this->profilerName()); // Uses `ret` to avoids `contains` invoking was optimized in release mode if (ret) { nodeVector.clear(); } } } , { "eraseObject", [=](){ Vector<Node*> nodeVector = createVector(); Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); for (int i = 0; i < quantityOfNodes; ++i) { nodes[i] = nodeVector.at(i); } CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.eraseObject(nodes[i]); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector.empty(), "nodeVector was not empty."); free(nodes); } } , { "erase", [=](){ Vector<Node*> nodeVector = createVector(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.erase(nodeVector.begin()); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector.empty(), "nodeVector was not empty."); } } , { "clear", [=](){ Vector<Node*> nodeVector = createVector(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.clear(); CC_PROFILER_STOP(this->profilerName()); CCASSERT(nodeVector.empty(), "nodeVector was not empty."); } } , { "swap by index", [=](){ Vector<Node*> nodeVector = createVector(); int swapIndex1 = quantityOfNodes / 3; int swapIndex2 = quantityOfNodes / 3 * 2; CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.swap(swapIndex1, swapIndex2); CC_PROFILER_STOP(this->profilerName()); } } , { "swap by object", [=](){ Vector<Node*> nodeVector = createVector(); Node* swapNode1 = nodeVector.at(quantityOfNodes / 3); Node* swapNode2 = nodeVector.at(quantityOfNodes / 3 * 2); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.swap(swapNode1, swapNode2); CC_PROFILER_STOP(this->profilerName()); } } , { "reverse", [=](){ Vector<Node*> nodeVector = createVector(); CC_PROFILER_START(this->profilerName()); for( int i=0; i<quantityOfNodes; ++i) nodeVector.reverse(); CC_PROFILER_STOP(this->profilerName()); } } , { "c++11 Range Loop", [=](){ Vector<Node*> nodeVector = createVector(); CC_PROFILER_START(this->profilerName()); for (const auto& e : nodeVector) { e->setTag(111); } CC_PROFILER_STOP(this->profilerName()); } } , }; for (const auto& func : testFunctions) { _testFunctions.push_back(func); } }
// on "init" you need to initialize your instance bool PageTest::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } scheduleUpdate(); percent = 0; Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto loadingBar = ui::LoadingBar::create("sliderProgress.png"); loadingBar->setTag(0); loadingBar->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); loadingBar->setPercent(percent); this->addChild(loadingBar); auto checkBox = ui::CheckBox::create("check_box_normal.png", "check_box_normal_press.png", "check_box_active.png", "check_box_normal_disable.png", "check_box_active_disable.png"); checkBox->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height - 100)); checkBox->addEventListener(CC_CALLBACK_2(PageTest::selectedEvent, this)); this->addChild(checkBox); auto slider = ui::Slider::create(); slider->loadBarTexture("sliderTrack.png"); slider->loadSlidBallTextures("sliderThumb.png", "sliderThumb.png", ""); slider->loadProgressBarTexture("sliderProgress.png"); slider->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height - 200)); slider->addEventListener(CC_CALLBACK_2(PageTest::sliderEvent, this)); this->addChild(slider); // auto recustom = ui::RichElementCustomNode::create(1, Color3B::WHITE, 255, pAr); // richText->pushBackElement(recustom); // androidだとバックグランドが緑がデフォ? // androidだと盤面全体が背景白になる // http://discuss.cocos2d-x.org/t/ui-pageview-bug-with-v3-rc1-green-background-on-android/12897 // auto layout = ui::Layout::create(); layout->setSize(Size(visibleSize.width, 200.0f)); layout->setPosition(Vec2::ZERO); layout->setBackGroundColorType(ui::Layout::BackGroundColorType::SOLID); layout->setBackGroundColor(Color3B::BLUE); this->addChild(layout); auto pageView = ui::PageView::create(); /* pageView->setBackGroundColorType(ui::Layout::BackGroundColorType::SOLID); pageView->setBackGroundColor(Color3B::RED); */ pageView->setSize(Size(visibleSize.width, 130.0f)); pageView->setPosition(Vec2::ZERO); pageView->setContentSize(Size(visibleSize.width, 130.0f)); for (int i = 0; i < 3; ++i) { auto layout = ui::Layout::create(); layout->setBackGroundImage(""); layout->setBackGroundColor(Color3B::YELLOW); layout->setBackGroundColorType(ui::Layout::BackGroundColorType::SOLID); layout->setSize(Size(240.0f, 130.0f)); // layout->addTouchEventListener(<#ccWidgetTouchCallback callback#>) auto imageView = ui::ImageView::create("HelloWorld.png"); imageView->setScale9Enabled(true); imageView->setSize(Size(240, 130)); imageView->setPosition(Vec2(layout->getSize().width / 2.0f, layout->getSize().height / 2.0f)); layout->addChild(imageView); auto label = ui::Text::create(StringUtils::format("page %d",(i+1)), "Arial", 30); label->setColor(Color3B(192, 192, 192)); label->setPosition(Vec2(layout->getSize().width / 2.0f, layout->getSize().height / 2.0f)); layout->addChild(label); auto btn = ui::Button::create(""); btn->setTitleText(""); btn->setTitleFontSize(12); btn->setTitleFontName(""); pageView->addPage(layout); } // pageView->scrollToPage(2); // うまくいかない。handleReleaseLogicのboundaryのためだと思われる pageView->addEventListener(CC_CALLBACK_2(PageTest::pageViewEvent, this)); layout->addChild(pageView); auto richText = ui::RichText::create(); richText->ignoreContentAdaptWithSize(false); richText->setSize(Size(100, 100)); richText->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height - 300)); this->addChild(richText); auto re1 = ui::RichElementText::create(1, Color3B::WHITE, 255, "This color is white. ", "Arial", 10); richText->pushBackElement(re1); auto re2 = ui::RichElementText::create(2, Color3B::YELLOW, 255, "This color is yellow. ", "Arial", 24); richText->insertElement(re2, 1); auto reimg = ui::RichElementImage::create(6, Color3B::WHITE, 255, "sliderballnormal.png"); richText->pushBackElement(reimg); return true; }
bool TestTimerService::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); float button_y_Offset =30; float y_pos = visibleSize.height-button_y_Offset; float x_pos = origin.x + visibleSize.width/2; /** * Back Button */ auto backButtonItem = MenuItemImage::create( "BackButton.png", "BackButton.png", CC_CALLBACK_1(TestTimerService::menuCloseCallback, this)); backButtonItem->setPosition(Point(x_pos ,origin.y + backButtonItem->getContentSize().height/2)); backButtonItem->setTag(GO_HOME); /** * CreateOrUpdateTimer */ auto createOrUpdateTimerLabel = LabelTTF::create("CreateOrUpdateTimer", "Marker Felt", 24); createOrUpdateTimerLabel->setColor(Color3B::WHITE); auto createOrUpdateTimerItem = MenuItemLabel::create(createOrUpdateTimerLabel, CC_CALLBACK_1(TestTimerService::createOrUpdateTimer, this)); createOrUpdateTimerItem->setPosition(Point(x_pos,y_pos)); /** * StartTimer */ auto startTimerLabel = LabelTTF::create("StartTimer", "Marker Felt", 24); startTimerLabel->setColor(Color3B::WHITE); auto startTimerItem = MenuItemLabel::create(startTimerLabel, CC_CALLBACK_1(TestTimerService::startTimer, this)); y_pos -= button_y_Offset; startTimerItem->setPosition(Point(x_pos,y_pos)); // create menu, it's an autorelease object auto menu = Menu::create(backButtonItem, createOrUpdateTimerItem, startTimerItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1); timerName = "app42Timer"; userName = "******"; return true; }