NewCullingTest::NewCullingTest() { Size size = Director::getInstance()->getWinSize(); auto sprite = Sprite::create("Images/btn-about-normal-vertical.png"); sprite->setRotation(5); sprite->setPosition(Vec2(size.width/2,size.height/3)); sprite->setScale(2); addChild(sprite); auto sprite2 = Sprite::create("Images/btn-about-normal-vertical.png"); sprite2->setRotation(-85); sprite2->setPosition(Vec2(size.width/2,size.height * 2/3)); sprite2->setScale(2); addChild(sprite2); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(NewCullingTest::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(NewCullingTest::onTouchMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); }
bool StageSelect::init() { if (Layer::init()) { selected_cell = nullptr; s_playerConfig.overstage = 50; if(s_playerConfig.overstage >=50 ) { s_playerConfig.overstage = 50; fake_overstage = 49; } else fake_overstage = s_playerConfig.overstage; _selectItem = fake_overstage; _noTouch = true ; isCloseClick = true; auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event* event){ return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto panelSize = Size(520,s_visibleRect.visibleHeight * 0.88f);//s_visibleRect.visibleWidth - 97 _cellSize.width = panelSize.width; _cellSize.height = 100; _panel = Scale9Sprite::create("mission.png"); _panel->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); _panel->setPosition(Point(s_visibleRect.center.x,s_visibleRect.top.y + panelSize.height)); _panel->setContentSize(panelSize); this->addChild(_panel); auto stageselect_text = TextSprite::create(s_gameStrings.mainMenu->stageselect.c_str()); stageselect_text->setAnchorPoint(Point::ANCHOR_MIDDLE); stageselect_text->setPosition(Point(panelSize.width/2, panelSize.height-170)); _panel->addChild(stageselect_text); //door effect. left_door = Sprite::create("door_l.png"); right_door = Sprite::create("door_r.png"); left_door->setScale(1.0f, 0.9f); right_door->setScale(1.0f, 0.9f); left_door->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); right_door->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); left_door->setPosition(Point(panelSize.width/2+25,panelSize.height/2-39)); right_door->setPosition(Point(panelSize.width/2-25,panelSize.height/2-39)); _panel->addChild(left_door,2); _panel->addChild(right_door,2); auto actionmovedone = CallFunc::create( [=](){ PLAY_OPENDOOR_EFFECT; auto size = left_door->getContentSize(); auto move = MoveBy::create(0.5, Point(-(size.width), 0)); left_door->runAction(move); left_door->runAction(ScaleTo::create(0.5, 0, 0.9f)); auto move1 = move->reverse(); right_door->runAction(move1); right_door->runAction(Sequence::create(ScaleTo::create(0.5, 0, 0.9f), CallFunc::create([=]() { PLAY_STAGELIST_EFFECT; isCloseClick = false; if(fake_overstage>2 && fake_overstage<47) tableView->setContentOffsetInDuration(tableView->getContentOffset() + Point(0,_cellSize.height*(fake_overstage-2)),fake_overstage*0.02f); else if(fake_overstage>=47) tableView->setContentOffsetInDuration(tableView->getContentOffset() + Point(0,_cellSize.height*45),46*0.02f); }), nullptr)); }); _panel->runAction(Sequence::create(MoveTo::create(0.15f,s_visibleRect.top), DelayTime::create(0.3f), actionmovedone,nullptr)); tableView = TableView::create(this, Size(panelSize.width, panelSize.height - 345)); tableView->setDirection(ScrollView::Direction::VERTICAL); tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN); tableView->setPosition(Point(0,135)); tableView->setDelegate(this); tableView->reloadData(); _panel->addChild(tableView,0); tableView->setTouchEnabled(false); runAction(Sequence::create(DelayTime::create(1.0f),CallFunc::create([=](){tableView->setTouchEnabled(true);}), nullptr)); auto itemClosed = MenuItemImageLabel::createWithFrameName("back_0.png","back_1.png", CC_CALLBACK_1(StageSelect::menuCallbackClosed,this)); itemClosed->setAnchorPoint(Point::ANCHOR_TOP_RIGHT); itemClosed->setPosition((s_visibleRect.visibleWidth + panelSize.width)/2,panelSize.height); auto itemFight = MenuItemImageLabel::createWithFrameName("btA_0.png","btA_1.png", CC_CALLBACK_1(StageSelect::menuCallbackFight,this), s_gameStrings.mainMenu->stage_fight.c_str()); itemFight->setPosition(Point(panelSize.width / 2,77)); itemFight->setTextColor(Color3B(255, 255, 0)); auto menu = Menu::create( itemClosed, itemFight, nullptr); menu->setPosition(Point::ZERO); _panel->addChild(menu); addBall(); return true; } return false; }
bool GamePlay::init() { if (!Layer::init()) { return false; } gameState = Ready; visibleSize = Director::getInstance()->getVisibleSize(); getSoundMusic(); //load game AI //init array number and computation int ARRAY_NUMBER[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; arrNum = gameAI->randomNumber(ARRAY_NUMBER, SUM_NUM); for (int i = 0; i < SUM_NUM; i++) { arrNUM[i] = arrNum[i]; } char s[SUM_COM] = ""; //TODO change level // arrCOM = gameAI->randomComputation(s, SUM_COM, // GamePlay::instance()->getLevel() >= 2 ? 2 : 3); arrCOM = gameAI->randomComputation(s, SUM_COM, 2); for (int i = 0; i < SUM_COM; i++) { arrCOMPUTATE[i] = arrCOM[i]; } for (int i = 0; i < SUM_COM / 2; i++) { tempResult[i] = INIT_FRAME; } int arr[GamePlay::instance()->getLevel()]; int* arrayLevel = gameAI->randomLessNumber(arr, GamePlay::instance()->getLevel()); //load background auto bg = Sprite::create("background.png"); bg->setAnchorPoint(Vec2(0, 0)); bg->setPosition(Vec2(0, 0)); this->addChild(bg, -1); float rX = visibleSize.width / bg->getContentSize().width; float rY = visibleSize.height / bg->getContentSize().height; bg->setScaleX(rX); bg->setScaleY(rY); //show logo game Sprite *logoGame = Sprite::create("smalllogo.png"); logoGame->setAnchorPoint(Vec2(0.0, 1.0)); logoGame->setPosition(Vec2(PADDING, visibleSize.height - PADDING)); logoGame->setTag(TAG_LOGO); logoGame->setScale(0.6f); this->addChild(logoGame); //load frame ready float baseY = logoGame->getPositionY() - logoGame->getBoundingBox().size.height - PADDING; float baseX = PADDING / 2; for (int i = 0; i < SUM_NUM; i++) { frameReady[i] = Sprite::create("frame.png"); float width = frameReady[i]->getContentSize().width; float height = frameReady[i]->getContentSize().height; frameReady[i]->setTag(TAG_START_READY_POINT + i); frameReady[i]->setPositionX(baseX + 5.0 / 8.0 * i * width + width / 2); if (i % 2 == 0) { frameReady[i]->setPositionY(baseY - height / 2); } else { frameReady[i]->setPositionY(baseY - height); } this->addChild(frameReady[i]); } //create frame play float paddingY = 0; float paddingX = 0; for (int i = 0; i < SUM_NUM; i++) { float baseX = PADDING; framePlay[i] = TouchSprite::create("frame.png"); framePlay[i]->setTag(TAG_FRAME_PLAY + i); paddingX = (visibleSize.width - PADDING * 4 - framePlay[i]->getContentSize().width) / 3.0; framePlay[i]->setPositionX( PADDING + framePlay[i]->getContentSize().width / 2 + paddingX * (i % 3)); float baseY = frameReady[0]->getPositionY(); if (i % 3 == 0) paddingY = paddingX * ((int) i / 3 + 1); framePlay[i]->setPositionY(baseY - paddingY); framePlay[i]->score = 0; framePlay[i]->isFixed = false; for (int j = 0; j < GamePlay::instance()->getLevel(); j++) { if (arrNum[i] == arrayLevel[j]) { framePlay[i]->score = arrNum[i]; //TODO framePlay[i]->isFixed = true; framePlay[i]->setDisplayFrame( SpriteFrame::create( "frame" + std::to_string(arrNum[i]) + ".png", framePlay[i]->getTextureRect())); } } // CCLog("frameplay[%d] = %d", i, framePlay[i]->score); this->addChild(framePlay[i]); } //load number button //TODO std::string name = "number"; MoveTo* actionBy; int k = 0; for (int i = 0; i < SUM_NUM; i++) { numberBtn[i] = TouchSprite::create( name + std::to_string(i + 1) + ".png"); numberBtn[i]->setTag(TAG_NUMBER + i); numberBtn[i]->setPositionY(visibleSize.height + 3 * PADDING); numberBtn[i]->setPositionX(frameReady[i]->getPositionX()); numberBtn[i]->setZOrder(10); numberBtn[i]->isHidden = false; this->addChild(numberBtn[i]); actionBy = MoveTo::create(0.4, frameReady[i]->getPosition()); auto easeAction = EaseBounceInOut::create(actionBy); for (int j = 0; j < GamePlay::instance()->getLevel(); j++) { if ((i + 1) == arrayLevel[j]) { numberBtn[i]->isHidden = true; numberBtn[i]->setVisible(false); } } if (numberBtn[i]->isHidden == false) { auto delay = DelayTime::create(0.2 * (k + 1)); auto sequence = Sequence::create(delay, easeAction, nullptr); numberBtn[i]->runAction(sequence); k++; } } if (frameReady != NULL) { for (int i = 0; i < SUM_NUM; i++) frameReady[i]->setVisible(false); } //create result frame and equal character Sprite* frameEqual[SUM_COM / 2]; Sprite* characterEqual[SUM_COM / 2]; for (int i = 0; i < SUM_COM / 2; i++) { characterEqual[i] = Sprite::create("icon_equal.png"); frameEqual[i] = Sprite::createWithTexture(frameReady[i]->getTexture()); frameEqual[i]->setTag(TAG_FRAME_EQUAL + i); if (i % 2 == 0) { //frame equal frameEqual[i]->setPositionY( framePlay[SUM_NUM - 1]->getPositionY() + paddingX * (2 - (int) i / 2)); frameEqual[i]->setPositionX( framePlay[SUM_NUM - 1]->getPositionX() + paddingX); //character equal characterEqual[i]->setPositionY( framePlay[SUM_NUM - 1]->getPositionY() + paddingX * ((int) i / 2)); characterEqual[i]->setPositionX( framePlay[SUM_NUM - 1]->getPositionX() + paddingX / 2); } else { //frame equal frameEqual[i]->setPositionY( framePlay[SUM_NUM - 1]->getPositionY() - paddingX); frameEqual[i]->setPositionX( framePlay[SUM_NUM - 1]->getPositionX() - paddingX * (2 - (int) i / 2)); //character equal characterEqual[i]->setPositionY( framePlay[SUM_NUM - 1]->getPositionY() - paddingX / 2); characterEqual[i]->setPositionX( framePlay[SUM_NUM - 1]->getPositionX() - paddingX * (2 - (int) i / 2)); } this->addChild(frameEqual[i]); this->addChild(characterEqual[i]); } //position of character computation Sprite* plusSprite = Sprite::create("icon_plus.png"); Sprite* minusSrite = Sprite::create("icon_minus.png"); Sprite* mutiplySprite = Sprite::create("icon_multiply.png"); Sprite* divideSprite = Sprite::create("icon_divide.png"); for (int i = 0; i < SUM_COM; i++) { if (arrCOM[i] == '+') comBtn[i] = Sprite::createWithTexture(plusSprite->getTexture()); else if (arrCOM[i] == '-') comBtn[i] = Sprite::createWithTexture(minusSrite->getTexture()); else if (arrCOM[i] == '*') comBtn[i] = Sprite::createWithTexture(mutiplySprite->getTexture()); else if (arrCOM[i] == '/') comBtn[i] = Sprite::createWithTexture(divideSprite->getTexture()); this->addChild(comBtn[i]); } setPosCharacterBtn(comBtn, framePlay, paddingX); //calculate result result[0] = gameAI->calculate(arrNum[0], arrNum[1], arrNum[2], arrCOM[0], arrCOM[1]); result[1] = gameAI->calculate(arrNum[0], arrNum[3], arrNum[6], arrCOM[2], arrCOM[7]); result[2] = gameAI->calculate(arrNum[3], arrNum[4], arrNum[5], arrCOM[5], arrCOM[6]); result[3] = gameAI->calculate(arrNum[1], arrNum[4], arrNum[7], arrCOM[3], arrCOM[8]); result[4] = gameAI->calculate(arrNum[6], arrNum[7], arrNum[8], arrCOM[10], arrCOM[11]); result[5] = gameAI->calculate(arrNum[2], arrNum[5], arrNum[8], arrCOM[4], arrCOM[9]); gameAI->printArray(result, SUM_COM / 2); //set result to frameEqual for (int i = 0; i < SUM_COM / 2; i++) { resultLabel[i] = LabelTTF::create("00:00", "fonts/hlvgchac.ttf", 48); resultLabel[i]->setColor(Color3B(Color3B::RED)); resultLabel[i]->setString(std::to_string(result[i])); resultLabel[i]->setPosition(frameEqual[i]->getPosition()); this->addChild(resultLabel[i]); } //button pause Sprite* pauseGame = Sprite::create("pauseBtn.png"); Sprite* pauseGame_press = Sprite::create("pauseBtn_press.png"); MenuItemSprite* pauseBtn = MenuItemSprite::create(pauseGame, pauseGame_press, NULL, CC_CALLBACK_0(GamePlay::gamePause, this)); Menu *menuPause = Menu::create(pauseBtn, nullptr); menuPause->setPosition( Vec2( visibleSize.width - PADDING - pauseBtn->getContentSize().width / 2, visibleSize.height - PADDING - pauseBtn->getContentSize().height / 2)); menuPause->setTag(TAG_PAUSE_BTN); this->addChild(menuPause); //time in pause button LabelTTF *currenttime = LabelTTF::create("00:00", "fonts/hlvgchac.ttf", 40); Point timePoint = menuPause->getPosition(); currenttime->setPosition( Vec2(timePoint.x - PADDING * 2, timePoint.y + 7.0 / 4.0 * PADDING)); currenttime->setZOrder(10); currenttime->setColor(Color3B(Color3B::RED)); currenttime->setTag(TAG_LABEL_COUNT_TIME); this->addChild(currenttime); std::string miniModeSprite = getLevelString( GamePlay::instance()->getLevel()); Sprite* miniMode = Sprite::create("mini" + miniModeSprite + ".png"); miniMode->setScale(0.5); miniMode->setPosition( Vec2(currenttime->getPositionX(), currenttime->getPositionY() - currenttime->getContentSize().height - PADDING / 2)); this->addChild(miniMode); //board menu pause boardMenuPause = Sprite::create("board.png"); boardMenuPause->setPosition( Vec2(visibleSize.width / 2, visibleSize.height + boardMenuPause->getContentSize().height / 2 + PADDING)); boardMenuPause->setZOrder(30); this->addChild(boardMenuPause); //button help of menu Sprite* helpbtn = Sprite::create("help1.png"); Sprite* helpbtn_press = Sprite::create("help2.png"); MenuItemSprite* helpBtn = MenuItemSprite::create(helpbtn, helpbtn_press, NULL, CC_CALLBACK_0(GamePlay::gameHelp, this)); Menu *menuHelp = Menu::create(helpBtn, nullptr); menuHelp->setPosition( Vec2(boardMenuPause->getContentSize().width / 2, boardMenuPause->getContentSize().height - helpbtn->getContentSize().height)); boardMenuPause->addChild(menuHelp); //button setting of menu Sprite* setbtn = Sprite::create("settings1.png"); Sprite* setbtn_press = Sprite::create("settings2.png"); MenuItemSprite* setBtn = MenuItemSprite::create(setbtn, setbtn_press, NULL, CC_CALLBACK_0(GamePlay::gameSetting, this)); Menu *menuSetting = Menu::create(setBtn, nullptr); menuSetting->setPosition( Vec2(boardMenuPause->getContentSize().width / 2, menuHelp->getPositionY() - setbtn->getContentSize().height - PADDING)); menuSetting->setTag(TAG_SETTING); boardMenuPause->addChild(menuSetting); //button quit of menu Sprite* quitbtn = Sprite::create("quit1.png"); Sprite* quitbtn_press = Sprite::create("quit2.png"); MenuItemSprite* quitBtn = MenuItemSprite::create(quitbtn, quitbtn_press, NULL, CC_CALLBACK_0(GamePlay::gameQuit, this)); Menu *menuQuit = Menu::create(quitBtn, nullptr); menuQuit->setPosition( Vec2(menuSetting->getPositionX(), menuSetting->getPositionY() - quitbtn->getContentSize().height - PADDING)); menuQuit->setTag(TAG_QUIT); boardMenuPause->addChild(menuQuit); //button replay, resume, share MenuItemImage* resumeBtn = MenuItemImage::create("menu_resume.png", "menu_resume.png", CC_CALLBACK_0(GamePlay::gameResume, this)); auto menuResume = Menu::create(resumeBtn, nullptr); menuResume->setPosition( Vec2(menuSetting->getPositionX(), menuQuit->getPositionY() - resumeBtn->getContentSize().height - PADDING)); boardMenuPause->addChild(menuResume); MenuItemImage* replayBtn = MenuItemImage::create("menu_replay.png", "menu_replay.png", CC_CALLBACK_0(GamePlay::gameReplay, this)); auto menuReplay = Menu::create(replayBtn, nullptr); menuReplay->setPosition( Vec2( menuResume->getPositionX() - resumeBtn->getContentSize().width - PADDING, menuResume->getPositionY())); boardMenuPause->addChild(menuReplay); MenuItemImage* shareBtn = MenuItemImage::create("menu_share.png", "menu_share.png", CC_CALLBACK_0(GamePlay::gameShareCloseMenuPause, this)); auto menuShare = Menu::create(shareBtn, nullptr); menuShare->setPosition( Vec2( menuResume->getPositionX() + resumeBtn->getContentSize().width + PADDING, menuResume->getPositionY())); boardMenuPause->addChild(menuShare); auto event_listener = EventListenerTouchOneByOne::create(); auto dispatcher = Director::getInstance()->getEventDispatcher(); event_listener->setSwallowTouches(true); event_listener->onTouchBegan = CC_CALLBACK_2(GamePlay::onTouchBegan, this); event_listener->onTouchMoved = CC_CALLBACK_2(GamePlay::onTouchMoved, this); event_listener->onTouchEnded = CC_CALLBACK_2(GamePlay::onTouchEnded, this); dispatcher->addEventListenerWithSceneGraphPriority(event_listener, this); this->setKeypadEnabled(true); this->scheduleUpdate(); // this->schedule(schedule_selector(GamePlay::update), 1.0f); gameState = Playing; return true; }
bool EndlessScene::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto returnItem = MenuItemImage::create( "endless/icon_back.png", "endless/icon_back.png", CC_CALLBACK_1(EndlessScene::returnCallback, this)); returnItem->setPosition(Vec2(origin.x + returnItem->getContentSize().width / 2, origin.y + visibleSize.height - returnItem->getContentSize().height / 2)); auto pauseItem = MenuItemImage::create( "endless/icon_pause.png", "endless/icon_pause.png", CC_CALLBACK_1(EndlessScene::pauseCallback, this)); pauseItem->setPosition(Vec2(origin.x + visibleSize.width - pauseItem->getContentSize().width / 2, origin.y + visibleSize.height - pauseItem->getContentSize().height / 2)); // create menu, it's an autorelease object auto menu = Menu::create(returnItem, pauseItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); //preload audio //AudioControl::preLoad(); //add background image setBgImage(); //addCatAnimation(); addTranshCan(); //添加玩家,该场景为单人模式 m_player = Player::create(); m_player->createPlayer(4); m_player->setTotalMoneySpritePos(0, -20); m_player->ScoreFrame()->setPosition(m_player->ScoreFrame()->getPositionX(),m_player->ScoreFrame()->getPositionY() + 100); m_player->setTotalMoneyNumPos(0, 100); this->addChild(m_player, 1); //添加计时器 m_cmTimer = CMTimer::create(); m_cmTimer->setTotalTime(5); m_cmTimer->createLabel(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 80), m_player, 3); this->addChild(m_cmTimer, 2); //飘字 m_flyWord[0] = FlyWord::create("flyword/+5.png", 1.0, Vec2(origin.x + visibleSize.width / 2 - 130, origin.y + visibleSize.height / 2), 50); this->addChild(m_flyWord[0], 2); m_flyWord[1] = FlyWord::create("flyword/+10.png", 1.0, Vec2(origin.x + visibleSize.width / 2 - 130, origin.y + visibleSize.height / 2), 50); this->addChild(m_flyWord[1], 2); m_flyWord[2] = FlyWord::create("flyword/+20.png", 1.0, Vec2(origin.x + visibleSize.width / 2 - 130, origin.y + visibleSize.height / 2), 50); this->addChild(m_flyWord[2], 2); m_flyWord[3] = FlyWord::create("flyword/+50.png", 1.0, Vec2(origin.x + visibleSize.width / 2 - 130, origin.y + visibleSize.height / 2), 50); this->addChild(m_flyWord[3], 2); m_flyWord[4] = FlyWord::create("flyword/+100.png", 1.0, Vec2(origin.x + visibleSize.width / 2 - 130, origin.y + visibleSize.height / 2), 50); this->addChild(m_flyWord[4], 2); //播放背景音乐 AudioControl::stopBGMusic(); AudioControl::playBgMusic(ENDLESS); //注册单点触屏事件 auto touchlistenter = EventListenerTouchOneByOne::create(); touchlistenter->setSwallowTouches(false); touchlistenter->onTouchBegan = CC_CALLBACK_2(EndlessScene::onTouchBegan, this); touchlistenter->onTouchEnded = CC_CALLBACK_2(EndlessScene::onTouchEnded, this); touchlistenter->onTouchMoved = CC_CALLBACK_2(EndlessScene::onTouchMoved, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchlistenter, this); //初始化 m_count_flag = false; m_moneyType = Real_100_S; m_nextMoneyType = Real_100_S; m_needRand = true; m_isEmpty = true; initProArr(); m_stage = 0; m_time_per_count = 1.0f; srand((unsigned)time(NULL)); addTargetNumLabel(); addStageLabel(); m_enabled = true; m_stageCount = 0; if (MCManual::novice[2]) { manualAct1(); } return true; }
// on "init" you need to initialize your instance bool Game::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); float width = visibleSize.width; float height = visibleSize.height; Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "Close1.png", "Close2.png", CC_CALLBACK_1(Game::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... this->drawWalls(width, height); this->drawPaddles(width, height); this->redrawPaddles(width, height); this->ball = Sprite::create("ball.png"); float ball_scale = (width / 32) / (WIDTH(this->ball)); this->ball->setScaleX(ball_scale); this->ball->setScaleY(ball_scale); this->addChild(this->ball); this->resetBall(); this->updateBall(); auto middleLine = Sprite::create("middleLine.png"); middleLine->setPosition(Vec2(origin.x + width / 2, origin.y + height / 2)); middleLine->setScaleY(height / middleLine->getContentSize().height); this->addChild(middleLine); this->label1 = Label::createWithTTF("A", "fonts/Marker Felt.ttf", 24); this->label1->setPosition(Vec2(width / 2 - 100, origin.y + height - WALL_HEIGHT - this->label1->getContentSize().height)); this->addChild(this->label1, 1); this->label2 = Label::createWithTTF("B", "fonts/Marker Felt.ttf", 24); this->label2->setPosition(Vec2(width / 2 + 100, origin.y + height - WALL_HEIGHT - this->label2->getContentSize().height)); this->addChild(this->label2, 1); this->updateScore(); this->p1UP = Rect(origin.x, origin.y + height / 2, origin.x + 150, origin.y + height); this->p1DOWN = Rect(origin.x, origin.y, origin.x + 150, origin.y + height / 2); this->p2UP = Rect(origin.x + width - 150, origin.y + height / 2, origin.x + width, origin.y + height); this->p2DOWN = Rect(origin.x + width - 150, origin.y, origin.x + width, origin.y + height / 2); auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); listener1->onTouchBegan = [](Touch* touch, Event* event){ auto game = static_cast<Game*>(event->getCurrentTarget()); Point location = game->convertToNodeSpace(touch->getLocation()); float height = Director::getInstance()->getVisibleSize().height; if (game->p1UP.containsPoint(location)) { game->player1Paddley += height / 15; } else if (game->p1DOWN.containsPoint(location)) { game->player1Paddley -= height / 15; } else if (game->p2UP.containsPoint(location)) { game->player2Paddley += height / 15; } else if (game->p2DOWN.containsPoint(location)) { game->player2Paddley -= height / 15; } return false; }; listener1->onTouchMoved = [](Touch* touch, Event* event){ }; listener1->onTouchEnded = [=](Touch* touch, Event* event){ }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this); this->schedule(schedule_selector(Game::update)); return true; }
bool LobbyScene::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); myInfoLayer = MyInfoLayer::create(); myInfoLayer->retain(); myInfoLayer->setAnchorPoint(Vec2(0, 0)); myInfoLayer->setPosition(Vec2(0, MY_INFO_LAYER_Y)); addChild(myInfoLayer, 0, TAG_MY_INFO_LAYER); menuButtonLayer = MenuButtonLayer::create(); menuButtonLayer->retain(); menuButtonLayer->setAnchorPoint(Vec2(0,0)); menuButtonLayer->setPosition(Vec2(0,0)); addChild(menuButtonLayer, 0, TAG_MENU_BUTTON_LAYER); lobbyGameLayer = LobbyGameLayer::create(); lobbyGameLayer->retain(); lobbyGameLayer->setAnchorPoint(Vec2(0, 0)); lobbyGameLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); lobbyChannelLayer = LobbyChannelLayer::create(); lobbyChannelLayer->retain(); lobbyChannelLayer->setAnchorPoint(Vec2(0, 0)); lobbyChannelLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); lobbyFriendLayer = LobbyFriendLayer::create(); lobbyFriendLayer->retain(); lobbyFriendLayer->setAnchorPoint(Vec2(0, 0)); lobbyFriendLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); lobbyClanLayer = LobbyClanLayer::create(); lobbyClanLayer->retain(); lobbyClanLayer->setAnchorPoint(Vec2(0, 0)); lobbyClanLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); lobbyRankingLayer = LobbyRankingLayer::create(); lobbyRankingLayer->retain(); lobbyRankingLayer->setAnchorPoint(Vec2(0, 0)); lobbyRankingLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); lobbyBoardLayer = LobbyBoardLayer::create(); lobbyBoardLayer->retain(); lobbyBoardLayer->setAnchorPoint(Vec2(0, 0)); lobbyBoardLayer->setPosition(Vec2(0, LOBBY_LAYER_Y)); addChild(lobbyGameLayer, 1, TAG_LOBBY_GAME_LAYER); currentLayer = CURRENT_LAYER_GAME; GameClient::GetInstance().currentScene = LOBBY_SCENE_NOW; // Size editboxSize = CCSizeMake(500, 70); // textBox = EditBox::create(editboxSize, Scale9Sprite::create("typefield_01.png")); // textBox->setAnchorPoint(ccp(0, 0)); // textBox->setPosition(ccp(0, 0)); // textBox->setFontSize(20); // textBox->setFontColor(ccWHITE); // textBox->setMaxLength(15); // textBox->setPlaceHolder("CHATTING"); // textBox->setReturnType(EditBox::KeyboardReturnType::DONE); // textBox->setInputMode(EditBox::InputMode::ANY); // textBox->setDelegate(this); // this->addChild(textBox); // menuLayer = Layer::create(); // menuLayer->setContentSize(Size(SCREEN_WIDTH / 4, SCREEN_HEIGHT)); // menuLayer->setAnchorPoint(Vec2(0, 0)); // menuLayer->setPosition(0, 0); // auto menuLayerbackGroundSprite = Sprite::create("back_ground_01.png"); // menuLayerbackGroundSprite->setAnchorPoint(Vec2(0, 0)); // menuLayerbackGroundSprite->setPosition(0, 0); // menuLayerbackGroundSprite->setScale((SCREEN_WIDTH / 4) / menuLayerbackGroundSprite->getContentSize().width, SCREEN_HEIGHT / menuLayerbackGroundSprite->getContentSize().height); // menuLayer->addChild(menuLayerbackGroundSprite, 0); // this->addChild(menuLayer, 100201); // // userListLayer = UserListLayer::create(); // userListLayer->setAnchorPoint(Vec2(0, 0)); // userListLayer->setPosition(Vec2(0, 0)); // userListLayer->setContentSize(Size(SCREEN_WIDTH / 4, SCREEN_HEIGHT * 2)); // // // scrollView = ScrollView::create(Size(SCREEN_WIDTH / 4, SCREEN_HEIGHT), userListLayer); // scrollView->retain(); // scrollView->setBounceable(false); // scrollView->setDirection(ScrollView::Direction::VERTICAL); // scrollView->setAnchorPoint(Vec2(0, 0)); // scrollView->setPosition(0, 0); // menuLayer->addChild(scrollView, 1); // scrollView->setContentOffset(Vec2(0, (-1 * userListLayer->getContentSize().height)), false); /* auto moveChannel = MenuItemImage::create( "channel_list.png", "channel_list.png", CC_CALLBACK_1(LobbyScene::GetChannelList, this)); moveChannel->setAnchorPoint(ccp(0, 0)); moveChannel->setPosition(0, 1000); auto userList = MenuItemImage::create( "user_list.png", "user_list.png", CC_CALLBACK_1(LobbyScene::GetUserList, this)); userList->setAnchorPoint(ccp(0, 0)); userList->setPosition(0, 900); auto friendList = MenuItemImage::create( "friend_list.png", "friend_list.png", CC_CALLBACK_1(LobbyScene::GetFriendList, this)); friendList->setAnchorPoint(ccp(0, 0)); friendList->setPosition(0, 800); auto roomList = MenuItemImage::create( "room_list.png", "room_list.png", CC_CALLBACK_1(LobbyScene::GetRoomList, this)); roomList->setAnchorPoint(ccp(0, 0)); roomList->setPosition(0, 700); auto requestList = MenuItemImage::create( "request_list.png", "request_list.png", CC_CALLBACK_1(LobbyScene::GetRequestList, this)); requestList->setAnchorPoint(ccp(0, 0)); requestList->setPosition(0, 600); int reqCount = GameClient::GetInstance().requestInfoCount; std::string reqCountStr; GameClient::intToString(reqCountStr, reqCount); requestCountLabel = LabelTTF::create(reqCountStr, "Arial", 24); requestCountLabel->setColor(Color3B(0, 0, 0)); requestCountLabel->setPosition(500, 650); menuLayer->addChild(requestCountLabel, 101); Menu* menu1 = Menu::create(moveChannel, userList, friendList, roomList, requestList, NULL); menu1->setAnchorPoint(ccp(0, 0)); menu1->setPosition(ccp(0, 0)); menuLayer->addChild(menu1, 100, TAG_MENU); channelListLayer = ChannelListLayer::create(); channelListLayer->retain(); userListLayer = UserListLayer::create(); userListLayer->retain(); roomListLayer = RoomListLayer::create(); roomListLayer->retain(); RoomInfo roomInfo[3]; memset(roomInfo, 0, sizeof(roomInfo)); for (int i = 0; i < 3; i++) { roomInfo[i].roomNo = i; memcpy(roomInfo[i].roomName, "room", sizeof(5)); } roomListLayer->SetRoomList(3, roomInfo); requestListLayer = RequestListLayer::create(); requestListLayer->retain(); requestListLayer->SetRequestList(); */ EventDispatcher* dispatcher = Director::getInstance()->getEventDispatcher(); //터치 위치를 알려주는 리스너. 단일 터치. //바로 만들어쓰는 식별자는 auto를 사용한다. auto positionListener = EventListenerTouchOneByOne::create(); //zOrder에 따라 밑에 깔린애도 동작할지 아닐지를 결정한다. positionListener->setSwallowTouches(true); //콜백 함수 대입 positionListener->onTouchBegan = CC_CALLBACK_2(LobbyScene::onTouchBegan, this); //디스패처를 이용해 객체와 리스너를 이어준다. 화면 전체를 터치할 수 있게 만들어야 하므로 객체는 this dispatcher->addEventListenerWithSceneGraphPriority(positionListener, this); return true; }
bool WindowProtocol::init(){ bool ret = false; //super init if(!Layer::init()) return ret; //Put blocker Layer* blocker = LayerColor::create(Color4B(0, 0, 0, 255*0.5), VisibleRect::getVisibleRect().size.width, VisibleRect::getVisibleRect().size.height); blocker->setAnchorPoint(Vec2::ZERO); blocker->setPosition(Vec2(VisibleRect::getVisibleRect().origin.x, VisibleRect::getVisibleRect().origin.y)); //Base window _baseWindow = Scale9Sprite::createWithSpriteFrameName("WindowBase.psd",BASE_WINDOW_INSET_RECT); _baseWindow->setContentSize(Size(850,490-10-10)); _baseWindow->setAnchorPoint(Vec2(0.0, 1.0)); _baseWindow->setPosition(Vec2(55, VisibleRect::getVisibleRect().size.height-60)); //Put base window _baseLayout = Layout::create(); CCASSERT(_baseLayout!=nullptr, "_baseLayout cannot be null."); _baseLayout->setLayoutType(Layout::Type::VERTICAL); _baseLayout->setContentSize(_baseWindow->getCapInsets().size); _baseLayout->setAnchorPoint(Vec2(0.0, 1.0)); _baseLayout->setPosition(Vec2(2,_baseWindow->getContentSize().height-2)); //PutLayout on sprite _baseWindow->addChild(_baseLayout,0); //---Title--- //Layout _titleLayout = Layout::create(); CCASSERT(_titleLayout!=nullptr, "_titleLayer cannot be null."); //_titleLayout->setAnchorPoint(Vec2(0.0, 1.0)); _titleLayout->setLayoutType(Layout::Type::HORIZONTAL); _titleLayout->setContentSize(Size(850-2*2, 55)); _titleLayout->setPosition(Vec2(_baseLayout->getContentSize().width/2, _baseLayout->getContentSize().height/2)); //set baseTitle as titleLayout background //No longer need title base image... _titleLayout->setBackGroundColorType(Layout::BackGroundColorType::SOLID); _titleLayout->setBackGroundColor(Color3B(200, 200, 169)); //Close Button LinearLayoutParameter* lpCloseButton = LinearLayoutParameter::create(); _closeButton = Button::create("MainUI_Windows_Close_Normal.png","MainUI_Windows_Close_Pressed.png","",TextureResType::PLIST); CCASSERT(_closeButton!=nullptr, "_closeButton cannot be null."); _closeButton->setPosition(Vec2(_titleLayout->getContentSize().width/2, _titleLayout->getContentSize().height/2)); lpCloseButton->setGravity(LinearLayoutParameter::LinearGravity::LEFT); lpCloseButton->setMargin(Margin(0, 0, 0, 0)); _closeButton->setLayoutParameter(lpCloseButton); if(_closeCallback!=nullptr) _closeButton->addTouchEventListener(_closeCallback); //Title text LinearLayoutParameter* lpTitleText = LinearLayoutParameter::create(); _titleText = Text::create(_titleString, "fonts/Apple_LiGothic_Medium.ttf", computeFontSize(42)); CCASSERT(_titleText!=nullptr, "_titletext cannot be null."); _titleText->setColor(Color3B(59,134,134)); _titleText->setPosition(Vec2(_titleLayout->getContentSize().width/2, _titleLayout->getContentSize().height/2)); lpTitleText->setGravity(LinearLayoutParameter::LinearGravity::CENTER_VERTICAL); lpTitleText->setMargin(Margin(_titleLayout->getContentSize().width/2-_titleText->getContentSize().width/2-_closeButton->getContentSize().width, 0, 0, 0)); _titleText->setLayoutParameter(lpTitleText); //Add component to title layout _titleLayout->addChild(_closeButton,1); _titleLayout->addChild(_titleText,2); //---add to base layout--- _baseLayout->addChild(_titleLayout); //setBlockerTouchDispatcher auto touchBlocker = EventListenerTouchOneByOne::create(); touchBlocker->setSwallowTouches(true); //lambda decide later touchBlocker->onTouchBegan= [](Touch* touch,Event* e){ return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(touchBlocker, blocker); //addChild addChild(blocker,0); addChild(_baseWindow,1); ret = true; return ret; }
bool ark_SwallowButton::init() { if (Layer::init()) { // Initialise instance variables _state=Control::State::NORMAL; setEnabled(true); setSelected(false); setHighlighted(false); auto dispatcher = Director::getInstance()->getEventDispatcher(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(Control::onTouchEnded, this); touchListener->onTouchCancelled = CC_CALLBACK_2(Control::onTouchCancelled, this); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); Scale9Sprite * backgroundSprite = Scale9Sprite::create(); Label *node = Label::createWithSystemFont("", "Helvetica", 12); CCASSERT(node != nullptr, "Label must not be nil."); LabelProtocol* label = dynamic_cast<LabelProtocol*>(node); CCASSERT(backgroundSprite != nullptr, "Background sprite must not be nil."); CCASSERT(label != nullptr || backgroundSprite != nullptr, ""); _parentInited = true; _isPushed = false; // Adjust the background image by default setAdjustBackgroundImage(true); setPreferredSize(Size::ZERO); // Zooming button by default _zoomOnTouchDown = true; _scaleRatio = 1.1f; // Set the default anchor point ignoreAnchorPointForPosition(false); setAnchorPoint(Point(0.5f, 0.5f)); // Set the nodes setTitleLabel(node); setBackgroundSprite(backgroundSprite); // Set the default color and opacity setColor(Color3B(255.0f, 255.0f, 255.0f)); setOpacity(255.0f); setOpacityModifyRGB(true); // Initialize the dispatch table setTitleForState(label->getString(), Control::State::NORMAL); setTitleColorForState(node->getColor(), Control::State::NORMAL); setTitleLabelForState(node, Control::State::NORMAL); setBackgroundSpriteForState(backgroundSprite, Control::State::NORMAL); setLabelAnchorPoint(Point(0.5f, 0.5f)); // Layout update needsLayout(); return true; } else { return false; } }
void HelloWorld::menuCloseCallback3(cocos2d::Ref* pSender) { CSound::getInstance()->preloadEffect("pew-pew-lei.wav"); CSound::getInstance()->playEffect("pew-pew-lei.wav"); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto SetLayer = LayerColor::create(Color4B(120,120,120,255)); auto SetLayerSize = SetLayer->getContentSize(); SetLayer->setScaleX(visibleSize.width/SetLayerSize.width); SetLayer->setScaleY(visibleSize.height/SetLayerSize.height); SetLayer->ignoreAnchorPointForPosition(false); SetLayer->setAnchorPoint(Vec2(0.5f,0.5f)); SetLayer->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); auto setbg = Sprite::create("picture/setbg.png"); auto setbgsize = setbg->getContentSize(); setbg->setScaleX(visibleSize.width/setbgsize.width); setbg->setScaleY(visibleSize.height/setbgsize.height); setbg->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); SetLayer->addChild(setbg); auto dis = Director::getInstance()->getEventDispatcher(); auto test = EventListenerTouchOneByOne::create(); test->setSwallowTouches(true); test->onTouchBegan = [=](Touch *pTouch, Event *pEvent)->bool{ return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(test,SetLayer); auto paihangbang = MenuItemImage::create( "picture/blue1_menu.png", "picture/blue2_menu.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback5,this)); paihangbang->setPosition(Vec2(origin.x + visibleSize.width - paihangbang->getContentSize().width/2-300 , origin.y + paihangbang->getContentSize().height/2+180)); paihangbang->setScale(0.8f); auto menu = Menu::create(paihangbang, NULL); menu->setPosition(Vec2::ZERO); SetLayer->addChild(menu, 1); #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 auto paihangbanglabel = Label::createWithTTF(Tools::Unicode2Utf8(L"排行榜"), "fonts/msyh.ttc", 30); #else auto paihangbanglabel = Label::createWithTTF("排行榜", "fonts/msyh.ttc", 30); #endif paihangbanglabel->setPosition(paihangbang->getPositionX(),paihangbang->getPositionY()); paihangbanglabel->setAnchorPoint(Vec2(0,0)); SetLayer->addChild(paihangbanglabel,1); string str; if (CSound::getInstance()->getIsPlay()) str = "picture/soundon1_cover.png"; else str = "picture/soundon2_cover.png"; auto musicsprite = Sprite::create(str); musicsprite->setPosition(Vec2(origin.x + visibleSize.width - musicsprite->getContentSize().width/2-320 , origin.y + musicsprite->getContentSize().height/2+400)); auto dis1 = Director::getInstance()->getEventDispatcher(); auto test1 = EventListenerTouchOneByOne::create(); test1->setSwallowTouches(true); test1->onTouchBegan = [=](Touch *pTouch, Event *pEvent)->bool{ Vec2 pos = pTouch->getLocation(); if (musicsprite->getBoundingBox().containsPoint(pos)) { if (CSound::getInstance()->getIsPlay()) { Texture2D* tex = Director::getInstance()->getTextureCache()->addImage("picture/soundon2_cover.png"); musicsprite->setTexture(tex); } else { Texture2D* tex = Director::getInstance()->getTextureCache()->addImage("picture/soundon1_cover.png"); musicsprite->setTexture(tex); } CSound::getInstance()->setIsPlay(!CSound::getInstance()->getIsPlay()); CSound::getInstance()->playBG("Butter-Fly.mp3",CSound::getInstance()->getIsPlay()); CReadFile::getInstance()->saveUserInfo(); return true; } return false; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(test1,musicsprite); SetLayer->addChild(musicsprite); auto back = MenuItemImage::create( "picture/pauseBackRoom.png", "picture/pauseBackRoom.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback4,this)); back->setPosition(Vec2(origin.x + visibleSize.width - back->getContentSize().width/2-310 , origin.y + back->getContentSize().height/2+280)); auto menu1 = Menu::create(back, NULL); menu1->setPosition(Vec2::ZERO); SetLayer->addChild(menu1, 1); this->addChild(SetLayer, 1); }
bool FloorMapLayer::init(int floor) { _floor = floor; // 由于直接继承自node,需要做一些处理,现在layer的功能全被废弃了,无意义 setContentSize(Director::getInstance()->getWinSize()); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(FloorMapLayer::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(FloorMapLayer::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // 加载地图编辑器文件 auto res = "TileMaps/floor00" + String::createWithFormat("%d", floor)->_string + ".tmx"; _tiled_map = cocos2d::experimental::TMXTiledMap::create(res); if (nullptr != _tiled_map) { _tiled_map->setPosition(Vec2(-50.0f, -50.0f)); this->addChild(_tiled_map); } // 路径节点 _road_node = Node::create(); if (nullptr != _road_node) { _road_node->setPosition(Vec2::ZERO); this->addChild(_road_node); } // 勇士骨骼动画节点 _warrior = WarriorNode::create(); /*cocostudio::CCBone* bone = _warrior->getBone("sheild1"); int index = bone->getDisplayManager()->getCurrentDisplayIndex(); bone->removeDisplay(1); bone->changeDisplayByIndex(-1, true); cocostudio::CCBone* bone2 = _warrior->getBone("sheild2"); index = bone2->getDisplayManager()->getCurrentDisplayIndex(); bone2->removeDisplay(1); bone2->changeDisplayByIndex(-1, true);*/ _warrior->setPosition(Vec2(62.5f, 62.5f)); this->addChild(_warrior); // 上方背景 auto inside_bg = Sprite::create("Images/bg_top2.png"); auto outside_bg = Sprite::create("Images/bg_top_1.png"); if (nullptr != outside_bg && nullptr != inside_bg) { auto win_size = Director::getInstance()->getWinSize(); outside_bg->setScale(inside_bg->getContentSize().width / outside_bg->getContentSize().width); outside_bg->setPosition(Vec2(win_size.width / 2, 1092.0f)); this->addChild(outside_bg); inside_bg->setPosition(Vec2(win_size.width / 2, 1076.0f)); this->addChild(inside_bg); } // 点击箭头节点 _arrow_node = ArrowNode::create(); if (nullptr != _arrow_node) { _arrow_node->setPosition(Vec2::ZERO); _arrow_node->setVisible(false); this->addChild(_arrow_node); } // 勇士属性面板 _info_panel = WarriorInfoPanel::create(); if (nullptr != _info_panel) { _info_panel->setPosition(Vec2(-10.0f, 825.0f)); this->addChild(_info_panel); } return true; }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } this->isGameOver = false; visibleSize = Director::getInstance()->getVisibleSize(); // Ground setup groundSprite0 = Sprite::create("ground.png"); this->addChild(groundSprite0); groundSprite0->setPosition(Vec2(groundSprite0->getContentSize().width/2.0 , groundSprite0->getContentSize().height/2)); groundSprite1 = Sprite::create("ground.png"); this->addChild(groundSprite1); groundSprite1->setPosition(Vec2(visibleSize.width + groundSprite1->getContentSize().width/2.0 -10, groundSprite1->getContentSize().height/2)); auto groundbody0 = PhysicsBody::createBox(groundSprite0->getContentSize()); groundbody0->setDynamic(false); groundbody0->setContactTestBitmask(true); groundSprite0->setPhysicsBody(groundbody0); auto groundbody1 = PhysicsBody::createBox(groundSprite1->getContentSize()); groundbody1->setDynamic(false); groundbody1->setContactTestBitmask(true); groundSprite1->setPhysicsBody(groundbody1); // SkyGround setup Sprite *skySprite0 = Sprite::create("flappy_background.png"); Sprite *skySprite1 = Sprite::create("flappy_background.png"); Sprite *skySprite2 = Sprite::create("flappy_background.png"); this->addChild(skySprite0); this->addChild(skySprite1); this->addChild(skySprite2); skySprite0->setPosition(visibleSize.width/2, 168 + 200); skySprite1->setPosition(visibleSize.width/2 - skySprite1->getContentSize().width, 168 + 200); skySprite2->setPosition(visibleSize.width/2 + skySprite1->getContentSize().width, 168 + 200); // bird setup /* Sprite *birdSprite = Sprite::create("flappybird1.png"); this->addChild(birdSprite); birdSprite->setPosition(visibleSize.width/2, visibleSize.height/2 + 120); */ SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("bird.plist"); auto flyAnim = Animation::create(); for (int i = 1; i < 4; i++) { SpriteFrame * frame = cache->getSpriteFrameByName("flappybird" + to_string(i) + ".png"); flyAnim->addSpriteFrame(frame); } auto birdSprite = Sprite::createWithSpriteFrameName("flappybird1.png"); flyAnim->setDelayPerUnit(0.2f); auto action = Animate::create(flyAnim); auto animation = RepeatForever::create(action); birdSprite->runAction(animation); birdSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2 + 80)); this->addChild(birdSprite); auto birdBody = PhysicsBody::createCircle(17.0); birdBody->setDynamic(true); birdBody->setMass(1.0f); birdBody->setVelocity(Vec2(4.0f, 2.0f)); birdBody->setVelocityLimit(50); birdBody->setContactTestBitmask(true); birdSprite->setPhysicsBody(birdBody); //pipe setup topPipeSprite = Sprite::create("top_pipe.png"); bottomPipeSprite = Sprite::create("bottom_pipe.png"); topPipeSprite->setPosition(visibleSize.width + topPipeSprite->getContentSize().width/2, 600); auto pipebody0 = PhysicsBody::createBox(topPipeSprite->getContentSize()); pipebody0->setDynamic(false); topPipeSprite->setPhysicsBody(pipebody0); pipebody0->setContactTestBitmask(true); auto pipebody1 = PhysicsBody::createBox(bottomPipeSprite->getContentSize()); pipebody1->setDynamic(false); pipebody1->setContactTestBitmask(true); bottomPipeSprite->setPhysicsBody(pipebody1); this->positionBottomPipe(); this->addChild(topPipeSprite); this->addChild(bottomPipeSprite); //setup touch listener auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [=](Touch *touch, Event *event){ if (!this->isGameOver) { birdBody->applyImpulse(Vec2(0, 90.0f)); } log("touch detected!"); return true; }; //setup collision listener auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = [=](PhysicsContact &contact){ log("collision detected!"); auto gameOverSprite = Sprite::create("game_over.png"); gameOverSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); this->addChild(gameOverSprite); this->isGameOver = true; auto restartListner = EventListenerTouchOneByOne::create(); restartListner->setSwallowTouches(true); restartListner->onTouchBegan = [](Touch *touch, Event* event){ Director::getInstance()->replaceScene(HelloWorld::createScene()); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(restartListner, gameOverSprite); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); this->scheduleUpdate(); return true; }
void GameMap::initActor() { TMXObjectGroup* group = this->objectGroupNamed("actor"); const ValueVector &objects = group->getObjects(); for (ValueVector::const_iterator it=objects.begin(); it!=objects.end(); it++) { const ValueMap &dict = (*it).asValueMap(); int x = dict.at("x").asInt(); int y = dict.at("y").asInt(); Vec2 pos = Vec2(x, y); std::string texture = dict.at("texture").asString(); CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(texture+".plist"); if (dict.at("enemy").asInt() == 0){ auto actor = ActorSprite::MyCreateInit(texture); //初始化属性值 actor->atk = dict.at("atk").asInt(); actor->Tag = dict.at("tag").asInt(); actor->life = dict.at("life").asInt(); actor->range = dict.at("range").asInt(); //增加了属性 actor->atkrange = dict.at("atkrange").asInt(); // auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(ActorSprite::onTouchBegan, actor); listener->onTouchEnded = CC_CALLBACK_2(ActorSprite::onTouchEnded, actor); listener->setSwallowTouches(true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, actor); //-----------------------改了,添加监听 actor->setPosition(pos+_tileSize/2); addChild(actor, 4); //增加血条 Sprite* bloodsp = Sprite::create("blood.png"); bloodsp->setScaleX(actor->life); bloodsp->setPosition(Vec2(actor->getContentSize().width/2, actor->getContentSize().height)); actor->addChild(bloodsp); bloodsp->setTag(actor->Tag); //增加血条 //把人物存放到容器中 friendArray.pushBack(actor); actor->setName(actor->ActorName); }else{ auto actor = EnemySprite::MyCreateInit(texture); actor->setOpacity(100); //初始化属性值 actor->atk = dict.at("atk").asInt(); actor->Tag = dict.at("tag").asInt(); actor->life = dict.at("life").asInt(); actor->range = dict.at("range").asInt(); actor->atkrange = dict.at("atkrange").asInt(); // auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(EnemySprite::onTouchBegan, actor); listener->onTouchEnded = CC_CALLBACK_2(EnemySprite::onTouchEnded, actor); listener->setSwallowTouches(true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, actor); //--------------------改了,添加监听 actor->setPosition(pos+_tileSize/2); addChild(actor, 4); Sprite* bloodsp = Sprite::create("blood.png"); bloodsp->setScaleX(actor->life); bloodsp->setPosition(Vec2(actor->getContentSize().width/2, actor->getContentSize().height)); actor->addChild(bloodsp); bloodsp->setTag(actor->Tag); //增加坏人存入vector中 enemyArray.pushBack(actor); actor->setName(actor->ActorName); } int width = dict.at("width").asInt(); int height = dict.at("height").asInt(); x /= width; y /= height; pos = Vec2(x, y); actorArray.insert(pos); } }
bool PopupLayer::initSuspendLayer(int gameType) { if(!LayerColor::initWithColor(Color4B(255, 255, 255, 120))) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); //set menu layer properties switch (userTheme) { case PINK: menuLayer = LayerColor::create(Color4B(234, 97, 137, 255)); break; case GRAY: menuLayer = LayerColor::create(Color4B(194, 194, 194, 255)); break; case BLUE: menuLayer = LayerColor::create(Color4B(20, 142, 204, 255)); break; case JELLY: menuLayer = LayerColor::create(Color4B(90, 191, 188, 255)); break; case DARK: menuLayer = LayerColor::create(Color4B(50, 50, 50, 255)); break; default: menuLayer = LayerColor::create(Color4B(20, 142, 204, 255)); break; } menuLayer->setContentSize(Size(350, 200)); menuLayer->ignoreAnchorPointForPosition(false); menuLayer->setAnchorPoint(Point(0.5, 0.5)); menuLayer->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); //add label "suspend" auto *suspendLabel = Label::create("Suspend", "Futura.ttf", 30); suspendLabel->setPosition(Point(menuLayer->getContentSize().width / 2, menuLayer->getContentSize().height / 2 + 50)); //add menus icons Sprite *homeButton = Sprite::create("home.png"); Sprite *activeHomeButton = Sprite::create("home.png"); activeHomeButton->setPositionY(5); auto homeMenuItem = MenuItemSprite::create(homeButton, activeHomeButton, NULL, CC_CALLBACK_1(PopupLayer::homeCallBack, this)); homeMenuItem->setPosition(menuLayer->getContentSize().width / 2 - 100, menuLayer->getContentSize().height / 2 - 30); auto homeMenu = Menu::create(homeMenuItem, NULL); homeMenu->setPosition(Point(0, 0)); Sprite *resumeButton = Sprite::create("start.png"); Sprite *activeResumeButton = Sprite::create("start.png"); activeResumeButton->setPositionY(5); MenuItemSprite *resumeMenuItem; if (gameType == 1) { resumeMenuItem = MenuItemSprite::create(resumeButton, activeResumeButton, NULL, CC_CALLBACK_1(PopupLayer::resumeNormalMode, this)); }else { resumeMenuItem = MenuItemSprite::create(resumeButton, activeResumeButton, NULL, CC_CALLBACK_1(PopupLayer::resumeGetTheOne, this)); } resumeMenuItem->setPosition(menuLayer->getContentSize().width / 2, menuLayer->getContentSize().height / 2 - 30); auto resumeMenu = Menu::create(resumeMenuItem, NULL); resumeMenu->setPosition(Point(0, 0)); Sprite *restartButton = Sprite::create("restart.png"); Sprite *activeRestartButton = Sprite::create("restart.png"); activeRestartButton->setPositionY(5); MenuItemSprite *restartMenuItem; if (gameType == 1) { restartMenuItem = MenuItemSprite::create(restartButton, activeRestartButton, NULL, CC_CALLBACK_1(PopupLayer::restartNormalMode, this)); }else{ restartMenuItem = MenuItemSprite::create(restartButton, activeRestartButton, NULL, CC_CALLBACK_1(PopupLayer::restartGetTheOne, this)); } restartMenuItem->setPosition(menuLayer->getContentSize().width / 2 + 100, menuLayer->getContentSize().height / 2 - 30); auto restartMenu = Menu::create(restartMenuItem, NULL); restartMenu->setPosition(Point(0, 0)); //add shadow for menuLayer auto *shadowLayer = LayerColor::create(Color4B(100, 100, 100, 100)); shadowLayer->setContentSize(Size(350, 200)); shadowLayer->ignoreAnchorPointForPosition(false); shadowLayer->setAnchorPoint(Point(0.5, 0.5)); shadowLayer->setPosition(Point(visibleSize.width / 2 + 8, visibleSize.height / 2 - 8)); menuLayer->addChild(suspendLabel); menuLayer->addChild(homeMenu); menuLayer->addChild(resumeMenu); menuLayer->addChild(restartMenu); this->addChild(shadowLayer); this->addChild(menuLayer); //swallow touch auto callback = [](Touch * ,Event *) { return true; }; //add event listener auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = callback; listener->setSwallowTouches(true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this); return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1); auto listener1 = EventListenerTouchOneByOne::create();//创建一个监听 listener1->setSwallowTouches(true);//设置是否想下传递触摸 listener1->onTouchBegan = [](Touch* touch, Event* event){ auto target = static_cast<Sprite*>(event->getCurrentTarget());//获取的当前触摸的目标 Point p = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); auto winsize = Director::getInstance()->getVisibleSize(); auto th_is = static_cast<HelloWorld*>(event->getCurrentTarget()); if (rect.containsPoint(p))//判断触摸点是否在目标的范围内 { if(winsize.height/winsize.width * p.x+p.y>winsize.height) { if(winsize.height/winsize.width * p.x<p.y && th_is->direction!=3) { log("up"); th_is->reSch(); th_is->move(1, th_is->snake.size()-1); }else if(winsize.height/winsize.width * p.x>p.y && th_is->direction!=4) { log("left"); th_is->reSch(); th_is->move(2, th_is->snake.size()-1); } }else { if(winsize.height/winsize.width * p.x<p.y && th_is->direction!=2) { log("right"); th_is->reSch(); th_is->move(4, th_is->snake.size()-1); } else if(winsize.height/winsize.width * p.x>p.y && th_is->direction!=1) { log("down"); th_is->reSch(); th_is->move(3, th_is->snake.size()-1); } } return true; }else return false; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this); this->apple = Sprite::create("bo.png"); apple->setAnchorPoint(Point(0,0)); apple->setPosition(Point(22*20,12*20)); apple->setColor(Color3B(255,0,0)); this->addChild(this->apple); auto head = Sprite::create("bo.png"); head->setAnchorPoint(Point(0,0)); head->setPosition(Point(2*20,12*20)); head->setColor(Color3B(0,255,0)); this->snake.pushBack(head); this->addChild(this->snake.at(0)); this->direction = 2; this->speed = 100; schedule(schedule_selector(HelloWorld::up_date), 60/this->speed); return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 5,40); ///////////////////////////// // 3. add your codes below... //添加定时器 schedule(schedule_selector(HelloWorld::update)); //!添加背景图片1 auto sprite = Sprite::create("images/background2.png"); sprite->setScaleX(2.5); sprite->setScaleY(2.5); // position the sprite on the center of the screen sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); //!添加背景图片2 auto sprite1=Sprite::create("images/backgroundBottom.png"); sprite1->setAnchorPoint(Point(0,0)); sprite1->setPosition(0,0); this->addChild(sprite1,2); //!添加游戏准备图片 auto sprite2 =Sprite::create("images/getready.png"); sprite2->setPosition(180,500); sprite2->setVisible(false); sprite2->setScaleX(2); sprite2->setScaleY(2); this->addChild(sprite2,2,2); //!添加游戏结束图片 auto sprite3=Sprite::create("images/gameover.png"); sprite3->setScaleX(2); sprite3->setScaleY(2); sprite3->setPosition(180,500); sprite3->setVisible(false); this->addChild(sprite3,2,3); this->setOpacity(0.0f); //!添加分数面板图片 auto sprite4=Sprite::create("images/scoreboard.png"); sprite4->setScaleX(2.5); sprite4->setScaleY(2.5); sprite4->setPosition(180,350); sprite4->setVisible(false); this->addChild(sprite4,2,4); sprite4->setOpacity(0.0f); //!添加分数面板分数字体 score=0; sprintf(b,"%d",score); auto fscores=LabelTTF::create(b,"Arial",25); this->addChild(fscores,5,100); fscores->setPosition(260,370); fscores->setVisible(false); //!添加一个新分数标志 auto newsprite=Sprite::create("images/newhighscore.png"); newsprite->setScale(2); newsprite->setAnchorPoint(Point(1.5,-1.0)); fscores->addChild(newsprite,1,1); newsprite->setVisible(false); //!添加分数面板最高分字体 this->getUserScore(); sprintf(c,"%d",userScore); auto fuscores=LabelTTF::create(c,"Arial",25); fuscores->setPosition(260,320); fuscores->setVisible(false); this->addChild(fuscores,5,101); //!添加重新开始按钮 auto restartItem = MenuItemImage::create("images/pauseRestart.png","images/pauseRestart1.png",CC_CALLBACK_1(HelloWorld::restartCallBack,this)); restartItem->setPosition(100,240); restartItem->setVisible(false); restartItem->setScale(0.7); menu->addChild(restartItem,0,1992); //!添加分数 sprintf(a,"scores:%d",score); auto scores=LabelTTF::create(a,"Arial",25); scores->setPosition(180,620); this->addChild(scores,4,10); //!添加事件 auto listener =EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan=CC_CALLBACK_2(HelloWorld::touchEvent,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this); //!添加雪花效果 auto snow=ParticleSnow::create(); auto texture=Director::getInstance()->getTextureCache(); snow->setTexture(texture->addImage("stars.png")); snow->setPosition(180,640); this->addChild(snow,2); //!添加滚动图片1 auto sbd1=Sprite::create("images/ground.png"); sbd1->setAnchorPoint(Point(0,0)); sbd1->setPosition(0,120); sbd1->setScale(2.2); this->addChild(sbd1,2,20); //!添加滚动图片2 auto sbd2=Sprite::create("images/ground.png"); sbd2->setAnchorPoint(Point(0,0)); sbd2->setPosition(360,120); sbd2->setScale(2.2); this->addChild(sbd2,2,21); //!添加游戏金币,该金币为玩家没玩一次游戏所得分数 auto goldsprite=Sprite::create("images/flappycoin.png"); goldsprite->setScale(1.5); goldsprite->setAnchorPoint(Point(1.2,0)); auto file=UserDefault::getInstance(); gameGold=file->getIntegerForKey("gameGold"); sprintf(d,"%d",gameGold); auto gold=LabelTTF::create(d,"Arial",20); gold->setPosition(45,580); gold->setAnchorPoint(Point(0,0)); gold->addChild(goldsprite); this->addChild(gold,3,25); srand(time(0)); _time=0.0f; //!设置当前状态 currState =gameReady::getInstance(); currState->enter(this); return true; }
void HPlayer::playerInit(const char * playerName) { Size size=Director::getInstance()->getWinSize(); Point origin = Director::getInstance()->getVisibleOrigin(); //设置飞船的位置在屏幕下面 Sprite *ship=Sprite::create(playerName); ship->setPosition(Point(origin.x+150,origin.y+120)); this->addChild(ship,0,ship_Tag); //设置参数(血量,当前血量,分数,无敌时间) hpMax=5; hp=5; score=0; strongTime=2*60;//60帧*2--->2秒 isStrong=false;//初始不是无敌状态,减血后会有一段时间的无敌状态 //添加右下角的血量Sprite for (int i=0; i<5; i++) { Sprite *shipHp=CCSprite::create("icon_hp.png"); //设置每个血量贴图在屏幕的右下角一次排列,并且从右至左tag分别是值为1,2,3,4,5的枚举类型 shipHp->setPosition(Point(size.width-20-30*i, shipHp->getContentSize().height*0.5)); if (i==0) { shipHp->setTag(tag_playerHP1); }else if(i==1){ shipHp->setTag(tag_playerHP2); }else if(i==2){ shipHp->setTag(tag_playerHP3); }else if(i==3){ shipHp->setTag(tag_playerHP4); }else if(i==4){ shipHp->setTag(tag_playerHP5); } //将每一个血量贴图添加到HWorld层中 HWorld::getInstance()->addChild(shipHp,10); } //添加分数Label Label *label=Label::createWithSystemFont("分数:", "Helvetica-Blood" , 24); //分数Label在屏幕位置左上方 label->setPosition(Point(200, size.height-22)); HWorld::getInstance()->addChild(label,10); //添加分数结果Label string strScore=Convert2String(score);//将score---转化为string类型 //此处需要的时char*类型,所以使用c_str()进行转换 Label * scoreLabel=Label::createWithSystemFont(strScore.c_str(), "Helvetica-Blood" , 24); scoreLabel->setPosition(Point(260, size.height-22)); //设置颜色为黄色 scoreLabel->setColor(Color3B(255, 255, 0)); HWorld::getInstance()->addChild(scoreLabel,10,scoreLabel_Tag); //添加杀敌Label Label *killLabel=Label::createWithSystemFont("杀敌:", "Helvetica-Blood", 24); killLabel->setPosition(Point(200, size.height-52)); HWorld::getInstance()->addChild(killLabel,10); //杀敌数结果Label string strKillCount=Convert2String(killCount);//将score---转化为string类型 strKillCount+="/100"; //C++中string可以直接拼接 //此处需要的时char*类型,所以使用c_str()进行转换 Label *labelKillCount=Label::createWithSystemFont(strKillCount.c_str(), "Helvetica-Blood", 24); labelKillCount->setPosition(Point(260, size.height-52)); //设置为黄色 labelKillCount->setColor(Color3B(255, 255, 0)); HWorld::getInstance()->addChild(labelKillCount,10,killLabel_Tag); //创建一个单点触摸监听 auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); //这个方法是指是否要吞噬触摸事件(也可以称之为是否穿透) listener1->onTouchBegan = [=](Touch* touch, Event* event) { //1、首先通过getCurrentTarget获取点击到的对象 auto target = static_cast<Sprite *>(event->getCurrentTarget()); //2、调用getLocation将iOS坐标系转换成cocos2d-x坐标系 Point locationInNode = target->convertToNodeSpace(touch->getLocation()); //3、然后调用convertToNodeSpace将上述cocos2d-x坐标系转换成该对象的本地坐标系 //4、通过调用getContentSize获取该对象的大小 Size s = target->getContentSize(); //5、创建该对象的frameRect Rect rect = Rect(0, 0, s.width, s.height); //6、将该触摸的本地坐标系与frameRect比较,若包含则表明触摸有效返回 if (rect.containsPoint(locationInNode)) { ///////////表示触摸到该对象,可进行一系列操作/////// return true;//表示寻找到该对象,并终止场景图事件监听遍历。—向下执行onTouchMoved, onTouchEnded } return false;//表示本次遍历不是该触摸对象,继续遍历下一个事件监听对象。 }; listener1->onTouchMoved = [=](Touch* touch, Event* event) { //强制类型转换 auto target = static_cast<Sprite*>(event->getCurrentTarget()); Point original = target->getPosition(); Point destination=touch->getDelta(); target->setPosition(Point(original.x+destination.x,original.y+destination.y)); //边界限定 float leftBorderLimit = target->getTexture()->getContentSize().width * 0.5f; float rightBorderLimit = size.width - target->getTexture()->getContentSize().width * 0.5f; float lowBorderLimit = target->getTexture()->getContentSize().width * 0.5f; float heightBorderLimit = size.height - target->getTexture()->getContentSize().width * 0.5f; if (original.x+destination.x<leftBorderLimit||original.x+destination.x>rightBorderLimit) { target->setPosition(Point(original.x,original.y+destination.y)); } if (original.y+destination.y<lowBorderLimit||original.y+destination.y>heightBorderLimit) { target->setPosition(Point(original.x+destination.x,original.y)); } }; listener1->onTouchEnded = [=](Touch* touch, Event* event) { }; //将触摸事件监听(listener1)加入到对象(ship)一个监听事件不能被添加给两个对象 _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, ship); }
bool Player::init() { //_Model = EffectSprite3D::createFromObjFileAndTexture("playerv002.c3b", "playerv002_256.png"); _Model = Sprite::create("mplane0_0.png"); if(_Model) { targetAngle = 0; targetPos = Vec2(0,0); _trailOffset = Vec2(0,-40); //_Model->setScale(8); addChild(_Model); // _Model->setRotation3D(Vec3(90,0,0)); _radius = 40; _HP = 100; _alive = true; _shadowType = kShadowSky; //airscrew Vector<SpriteFrame*> frames; for (int i = 0; i < 2; i++) { auto pic = String::createWithFormat("mscrew0_%d.png", i); auto frame = SpriteFrame::create(pic->getCString(), Rect(0,0,85,71)); frames.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(frames, 0.01f); auto animate = Animate::create(animation); auto screw = Sprite::createWithSpriteFrame(frames.at(0)); frames.clear(); /*screw->setPosition(_Model->getPositionX(), _Model->getPositionY()+_Model->getContentSize().height/2);*/ screw->runAction(RepeatForever::create(animate)); this->addChild(screw); ShadowController::createShadow(this); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(Player::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(Player::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(Player::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //scheduleUpdate(); //GameEntity::UseOutlineEffect(static_cast<Sprite3D*>(_Model), 0.02, Color3B(0,0,0)); schedule(schedule_selector(Player::shootMissile), 1.5, -1, 0); schedule(schedule_selector(Player::shoot), 0.075, -1, 0); // engine trail /* auto part_frame=SpriteFrameCache::getInstance()->getSpriteFrameByName("engine2.jpg"); ValueMap vm=ParticleManager::getInstance()->GetPlistData("engine"); auto part = ParticleSystemQuad::create(vm); part->setTextureWithRect(part_frame->getTexture(), part_frame->getRect()); addChild(part); part->setPosition(0,-30); part->setScale(0.6);*/ //part->setRotation(90); //controller support ios and android #if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) //need include base/CCEventListenerController.h and base/CCController.h文件 auto controlListener = EventListenerController::create(); controlListener->onKeyDown = CC_CALLBACK_3(Player::onKeyDown,this); controlListener->onKeyUp = CC_CALLBACK_3(Player::onKeyUp,this); controlListener->onAxisEvent = CC_CALLBACK_3(Player::onAxisEvent,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(controlListener,this); Controller::startDiscoveryController(); //init this->axisX = 0; this->axisY = 0; this->keyX = 0; this->keyY = 0; #endif return true; } return false; }
bool WorldTwo::init() { App::get()->setCurrentWorld(1); if (!LayerColor::initWithColor(Color4B(0, 0, 0, 255))) { return false; } #ifdef _WIN32 //install controler buttons App::get()->_player->clear_controller(); App::get()->_player->setButtomFunction([]{ Director::getInstance()->end(); }, CXBOXController::BUTTON_BACK); App::get()->_player->setButtomFunction([this] { if (App::get()->getCurrentMap() <= 0) App::get()->setCurrentMap(COUNT_LVLS_ON_1_WORLD - 1); else App::get()->decrementCurrnetMap(); _arrow->setPosition(Vec2(215 + _deltaX * (App::get()->getCurrentMap() % 5), 680 - _deltaY * (App::get()->getCurrentMap() / 5))); }, CXBOXController::BUTTON_LEFT); App::get()->_player->setButtomFunction([this] {if (App::get()->getCurrentMap() >= COUNT_LVLS_ON_1_WORLD - 1) App::get()->setCurrentMap(0); else App::get()->incrementCurrnetMap(); _arrow->setPosition(Vec2(215 + _deltaX * (App::get()->getCurrentMap() % 5), 680 - _deltaY * (App::get()->getCurrentMap() / 5))); }, CXBOXController::BUTTON_RIGHT); App::get()->_player->setButtomFunction([this]{ App::get()->startLevel(NULL); }, CXBOXController::BUTTON_START); App::get()->_player->setButtomFunction([this]{ App::get()->startLevel(NULL); }, CXBOXController::BUTTON_A); App::get()->_player->setButtomFunction([this]{ App::get()->gotoWorldMap(NULL); }, CXBOXController::BUTTON_B); #endif auto backBtn = MenuItemImage::create("back.png", "back.png", [](Ref*) { App::get()->gotoWorldMap(NULL); }); auto wiew = Director::getInstance()->getOpenGLView()->getDesignResolutionSize(); backBtn->setAnchorPoint(Vec2(0, 1)); backBtn->setPosition(Vec2(0, wiew.height)); auto menu = Menu::create(backBtn, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 2); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto sprite = Sprite::create("papirus_live.png"); sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); addChild(sprite, 0); auto deltaX = 0; auto deltaY = 0; //auto city1 = Sprite::create("leaf.png"); for (auto i = 0; i < COUNT_LVLS_ON_1_WORLD; i++) { Sprite* temp; if (App::get()->getConfig()._complitedLvls[1][i] == false) temp = Sprite::create("leaf_black.png"); else temp = Sprite::create("leaf.png"); _levels.push_back(temp); } for (auto i = 0; i < COUNT_LVLS_ON_1_WORLD; i++) { _levels[i]->setPosition(Vec2(220 + deltaX, 600 + deltaY)); addChild(_levels[i], 1); if ((i + 1) % 5 == 0) { deltaY -= 130; deltaX = 0; } else { deltaX += 135; } } auto listener = cocos2d::EventListenerTouchOneByOne::create(); _listener = listener; listener->setSwallowTouches(true); listener->onTouchBegan = [this](cocos2d::Touch* touch, cocos2d::Event* event) { cocos2d::Vec2 p = touch->getLocation(); for (auto i = 0; i < COUNT_LVLS_ON_1_WORLD; i++) { if (_levels[i]->getBoundingBox().containsPoint(p) && App::get()->canTouch()) { App::get()->setCurrentMap(i); App::get()->startLevel(NULL); return true; } } return false; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 30); #ifdef _WIN32 _arrow = Sprite::create("down_arrow.png"); _arrow->setPosition(Vec2(215 + _deltaX * (App::get()->getCurrentMap() % 5), 680 - _deltaY * (App::get()->getCurrentMap() / 5))); addChild(_arrow, 1); // Create the actions auto moveDown = MoveBy::create(.7, Point(0, -15)); auto moveUp = MoveBy::create(.7, Point(0, 15)); _arrow->runAction(RepeatForever::create(Sequence::create(moveDown, moveUp, NULL))); #endif this->schedule(schedule_selector(WorldTwo::update)); return true; }
bool GameOverLayer::init(bool win, int stage, int time, int kill, int loss, int newFlight) { if(!Layer::init()) { return false; } //init _stage = stage; std::string fontFile = "DS-Digital.ttf";//"arial.ttf"; int fontSize = 25; auto infoColor = DIY_COLOR_BLUE5; //swallow touches auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event* event){ return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //panel Size panelSize; if(win) panelSize = Size(s_visibleRect.visibleWidth-60,s_visibleRect.visibleHeight-280); else panelSize = Size(s_visibleRect.visibleWidth-60,s_visibleRect.visibleHeight-450); auto _panel = Scale9Sprite::create("windowBox.png"); _panel->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); _panel->setPosition(Point(s_visibleRect.center.x,s_visibleRect.top.y + panelSize.height)); _panel->setContentSize(panelSize); this->addChild(_panel); _panel->runAction(MoveTo::create(0.15f,s_visibleRect.top-Point(0,80))); //title TextSprite* title; if(win) { title = TextSprite::create(s_gameStrings.battleInfo->gameovertitle_win.c_str(),s_gameConfig.defaultFontName,32); title->setColor(Color3B::YELLOW); } else { title = TextSprite::create(s_gameStrings.battleInfo->gameovertitle_loss.c_str(),s_gameConfig.defaultFontName,32); title->setColor(Color3B::RED); } title->setAnchorPoint(Point::ANCHOR_MIDDLE); title->setPosition(Point(panelSize.width/2,panelSize.height-90)); _panel->addChild(title,1); //info auto time_label = TextSprite::create(s_gameStrings.battleInfo->gameovertime, "Arial", fontSize); time_label->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); time_label->setPosition(Point(150,panelSize.height-150)); _panel->addChild(time_label); time = time > 36000?3599:(time/10); int min = time/60; int sec = time - min*60; char p[10]; sprintf(p,"%02d\'%02d\"",min,sec); auto time_content = TextSprite::create(p,fontFile, fontSize); time_content->setColor(infoColor); time_content->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); time_content->setPosition(Point(320,panelSize.height-150)); _panel->addChild(time_content); auto kill_label = TextSprite::create(s_gameStrings.battleInfo->gameoverkill, "Arial", fontSize); kill_label->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); kill_label->setPosition(Point(150,panelSize.height-200)); _panel->addChild(kill_label); auto kill_content = TextSprite::create(Value(kill).asString(),fontFile, fontSize); kill_content->setColor(infoColor); kill_content->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); kill_content->setPosition(Point(320,panelSize.height-200)); _panel->addChild(kill_content); auto loss_label = TextSprite::create(s_gameStrings.battleInfo->gameoverloss, "Arial", fontSize); loss_label->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); loss_label->setPosition(Point(150,panelSize.height-250)); _panel->addChild(loss_label); auto loss_content = TextSprite::create(Value(loss).asString(), fontFile, fontSize); loss_content->setColor(infoColor); loss_content->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); loss_content->setPosition(Point(320,panelSize.height-250)); _panel->addChild(loss_content); //rewards if (win) { //init rewards int _gem = s_stageRewards[_stage][0]; int _starboom = s_stageRewards[_stage][1]; int _laser = s_stageRewards[_stage][2]; int _blackhole = s_stageRewards[_stage][3]; auto rewards_label = TextSprite::create(s_gameStrings.battleInfo->gameoverreward, "Arial", fontSize); rewards_label->setColor(Color3B::GRAY); rewards_label->setAnchorPoint(Point::ANCHOR_MIDDLE); rewards_label->setPosition(Point(panelSize.width/2,panelSize.height-300)); _panel->addChild(rewards_label); if(_starboom == 0 && _laser == 0 && _blackhole == 0) { auto icon = Sprite::createWithSpriteFrameName("icon_gem.png"); icon->setPosition(panelSize.width/2-50, panelSize.height/2-10); _panel->addChild(icon); auto label = Label::createWithTTF(Value(_gem).asString().c_str(), s_gameConfig.defaultFontName, fontSize); label->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); label->setPosition(Point(icon->getPositionX()+icon->getContentSize().width, icon->getPositionY())); label->setColor(Color3B::YELLOW); _panel->addChild(label); } else { auto icon1 = Sprite::createWithSpriteFrameName("icon_gem.png"); icon1->setPosition(panelSize.width/2-130, panelSize.height/2-10); _panel->addChild(icon1); auto label1 = Label::createWithTTF(Value(_gem).asString().c_str(), s_gameConfig.defaultFontName, fontSize); label1->setPosition(icon1->getPositionX()+icon1->getContentSize().width+20, icon1->getPositionY()); label1->setColor(Color3B::YELLOW); _panel->addChild(label1); if (_starboom > 0) { auto icon2 = Sprite::createWithSpriteFrameName("bomb_1_1.png"); icon2->setScale(0.5f);icon2->setRotation(90); icon2->setPosition(panelSize.width/2+50, panelSize.height/2-10); _panel->addChild(icon2); std::string str = "x" + Value(_starboom).asString(); auto label2 = Label::createWithTTF(str.c_str(), s_gameConfig.defaultFontName, fontSize); label2->setPosition(icon2->getPositionX()+icon2->getContentSize().width, icon2->getPositionY()); label2->setColor(infoColor); _panel->addChild(label2); } else if (_laser > 0) { auto icon2 = Sprite::createWithSpriteFrameName("bomb_2_1.png"); icon2->setScale(0.8f);icon2->setRotation(90); icon2->setPosition(panelSize.width/2+50, panelSize.height/2-10); _panel->addChild(icon2); std::string str = "x" + Value(_laser).asString(); auto label2 = Label::createWithTTF(str.c_str(), s_gameConfig.defaultFontName, fontSize); label2->setPosition(icon2->getPositionX()+icon2->getContentSize().width, icon2->getPositionY()); label2->setColor(infoColor); _panel->addChild(label2); } else if (_blackhole > 0) { auto icon2 = Sprite::createWithSpriteFrameName("bomb_3_1.png"); icon2->setScale(0.6f); icon2->setPosition(panelSize.width/2+50, panelSize.height/2); _panel->addChild(icon2); std::string str = "x" + Value(_blackhole).asString(); auto label2 = Label::createWithTTF(str.c_str(), s_gameConfig.defaultFontName, fontSize); label2->setPosition(icon2->getPositionX()+icon2->getContentSize().width, icon2->getPositionY()); label2->setColor(infoColor); _panel->addChild(label2); } } if(newFlight) { auto newflight_label = TextSprite::create(s_gameStrings.battleInfo->gameovernewflight, "Arial", fontSize); newflight_label->setColor(Color3B::GRAY); newflight_label->setAnchorPoint(Point::ANCHOR_MIDDLE); newflight_label->setPosition(Point(panelSize.width/2,panelSize.height-400)); _panel->addChild(newflight_label); char name[30]; sprintf(name,"plain_%d_lv_%d.png",newFlight,1); auto newflight = Sprite::createWithSpriteFrameName(name); newflight->setScale(1.3f); newflight->setAnchorPoint(Point::ANCHOR_MIDDLE); newflight->setPosition(Point(panelSize.width/2,panelSize.height-480)); _panel->addChild(newflight); auto newicon = Sprite::createWithSpriteFrameName("icon_new.png"); newicon->setAnchorPoint(Point::ANCHOR_MIDDLE); newicon->setPosition(newflight->getPosition()+Point(0,-60)); _panel->addChild(newicon); } } if(newFlight) { auto gotosee_menu = MenuItemImageLabel::createWithFrameName("bt_main_0.png", "bt_main_1.png", CC_CALLBACK_1(GameOverLayer::returnBase_callback, this), s_gameStrings.battleInfo->gotosee); gotosee_menu->setAnchorPoint(Point::ANCHOR_MIDDLE); gotosee_menu->setPosition(Point(panelSize.width/2, 60)); auto menu = Menu::create(gotosee_menu, nullptr); menu->setPosition(Point::ZERO); _panel->addChild(menu); return true; } //menu auto returnBase_menu = MenuItemImageLabel::createWithFrameName("bt_main_0.png", "bt_main_1.png", CC_CALLBACK_1(GameOverLayer::returnBase_callback, this), s_gameStrings.battleInfo->returnbase); returnBase_menu->setAnchorPoint(Point::ANCHOR_MIDDLE); returnBase_menu->setPosition(Point(panelSize.width/2, 150)); if (win && s_playerConfig.overstage<50) { auto nextStage_menu = MenuItemImageLabel::createWithFrameName("bt_main_0.png", "bt_main_1.png", CC_CALLBACK_1(GameOverLayer::nextStage_callback, this), s_gameStrings.battleInfo->nextstage); nextStage_menu->setAnchorPoint(Point::ANCHOR_MIDDLE); nextStage_menu->setPosition(Point(panelSize.width/2, 70)); nextStage_menu->setColor(DIY_COLOR_BLUE5); auto menu = Menu::create(returnBase_menu, nextStage_menu, nullptr); menu->setPosition(Point::ZERO); _panel->addChild(menu); } else{ auto restartStage_menu = MenuItemImageLabel::createWithFrameName("bt_main_0.png", "bt_main_1.png", CC_CALLBACK_1(GameOverLayer::restartStage_callback, this), s_gameStrings.battleInfo->restartstage); restartStage_menu->setAnchorPoint(Point::ANCHOR_MIDDLE); restartStage_menu->setPosition(Point(panelSize.width/2, 70)); auto menu = Menu::create(returnBase_menu, restartStage_menu, nullptr); menu->setPosition(Point::ZERO); _panel->addChild(menu); } //this->scheduleOnce(schedule_selector(GameOverLayer::pausegame), 0.5f); return true; }
bool UpgradeUILayer::init(BasePanel basePanel, int index) { if(!Layer::init()) return false; std::string fontFile = "DS-Digital.ttf";//"arial.ttf"; int fontSize = 25; auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event* event){ return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); panelSize = Size(s_visibleRect.visibleWidth-100,s_visibleRect.visibleHeight-500); _panel = Scale9Sprite::create("windowBox.png"); _panel->setAnchorPoint(Point::ANCHOR_MIDDLE); _panel->setPosition(Point(s_visibleRect.center.x,s_visibleRect.center.y + 100)); _panel->setContentSize(panelSize); this->addChild(_panel); _panel->setScale(0.1f); _panel->runAction(Sequence::create(ScaleTo::create(0.2f, 1.1f), ScaleTo::create(0.1f, 0.9f), ScaleTo::create(0.1f, 1.0f), nullptr)); auto itemClosed = MenuItemImageLabel::createWithFrameName("close_0.png","close_1.png", CC_CALLBACK_1(UpgradeUILayer::menuCallbackClosed,this)); itemClosed->setAnchorPoint(Point::ANCHOR_TOP_RIGHT); itemClosed->setPosition((s_visibleRect.visibleWidth + panelSize.width)/2-5,panelSize.height+35); auto menu = Menu::create( itemClosed, nullptr); menu->setPosition(Point::ZERO); _panel->addChild(menu,3); _basePanel = basePanel; _index = index; //title std::string title_text; switch (_basePanel) { case BasePanel::Toppanel: title_text = s_gameStrings.base->sparRecoverRate; break; case BasePanel::MiddlePanel: title_text = s_gameStrings.base->sparCapacity; break; case BasePanel::FlightPanel: title_text = s_gameStrings.base->flightname[_index]; break; case BasePanel::WeaponPanel: title_text = s_gameStrings.base->weaponname[_index-FIGHTER_MAX]; break; default: break; } auto tittle = TextSprite::create(title_text,GameConfig::defaultFontName,30, Size(500,30),TextHAlignment::CENTER,TextVAlignment::CENTER); tittle->setColor(DIY_COLOR_YELLOW5); tittle->setAnchorPoint(Point::ANCHOR_MIDDLE); tittle->setPosition(Point(panelSize.width/2,panelSize.height-40)); _panel->addChild(tittle); //upgrade button auto menuitem = MenuItemImageLabel::createWithFrameName("bt_main_0.png","bt_main_1.png",CC_CALLBACK_1(UpgradeUILayer::menuCallbackUpgrade,this)); menuitem->setScale(1.2f,0.7f); menuitem->setPosition(Point(panelSize.width / 2,40)); auto menuupgrade = Menu::create(menuitem,nullptr); menuupgrade->setPosition(Point::ZERO); _panel->addChild(menuupgrade); auto spar = Sprite::createWithSpriteFrameName("icon_gem.png"); spar->setPosition(Point(panelSize.width/2-110,40)); _panel->addChild(spar); auto upgradeText = TextSprite::create(s_gameStrings.base->upgrade,GameConfig::defaultFontName,fontSize); upgradeText->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); upgradeText->setPosition(panelSize.width/2+30,40); _panel->addChild(upgradeText); switch (_basePanel) { case BasePanel::Toppanel: _needgem = s_stoneSpeed[s_playerConfig.stonespeedlevel].gemForUpgrade; break; case BasePanel::MiddlePanel: _needgem = s_stoneCapacity[s_playerConfig.stonecapacitylevel].gemForUpgrade; break; case BasePanel::FlightPanel: _needgem = s_plainConfigs[_index][s_playerConfig.fighterslevel[_index]].gemForUpgrade; break; case BasePanel::WeaponPanel: _needgem = s_weaponConfigs[_index-FIGHTER_MAX][s_playerConfig.weaponslevel[_index-FIGHTER_MAX]].gemForUpgrade; break; default: break; } auto gemforUpgradeText = TextSprite::create(Value(_needgem).asString(),GameConfig::defaultFontName,fontSize); gemforUpgradeText->setColor(Color3B::YELLOW); gemforUpgradeText->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); gemforUpgradeText->setPosition(panelSize.width/2-90,40); _panel->addChild(gemforUpgradeText); //content switch (basePanel) { case BasePanel::Toppanel: createStoneSpeedUI(); break; case BasePanel::MiddlePanel: createStoneMaxUI(); break; case BasePanel::FlightPanel: createFlightUI(); break; case BasePanel::WeaponPanel: createWeaponUI(); break; default: break; } return true; }
bool PlaneLayer::init() { //没默认是活的 isAlive = true; CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("shoot.plist"); auto hero = Sprite::create("hero1.png"); Size contentSize = Director::sharedDirector()->getWinSize(); hero->setPosition(Point(contentSize.width / 2, hero->getContentSize().height / 2));//把飞机放在中间 hero->setAnchorPoint(Point(0.5,0.5)); this->addChild(hero,0,AIRPLANE); //给飞机添加闪烁动画 Blink* blink = Blink::create(1, 3); Animation* animation = Animation::create(); animation->setDelayPerUnit(0.1f); animation->addSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("hero1.png")); animation->addSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("hero2.png")); //帧动画 Animate* animate = Animate::create(animation); hero->runAction(blink); hero->runAction(CCRepeatForever::create(animate)); auto onTouchListener = EventListenerTouchOneByOne::create(); onTouchListener->setSwallowTouches(true); onTouchListener->onTouchBegan = [](Touch* touch, Event* event) { log("touched"); return true; }; onTouchListener->onTouchMoved = [](Touch* touch, Event* event) { //// 获取事件所绑定的 target auto target = static_cast<PlaneLayer*>(event->getCurrentTarget()); //获取当前屏幕宽高 auto winSize = CCDirector::getInstance()->getWinSize(); //获取当前点击点所在相对按钮的位置坐标 Point locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); //获得当前滑动触摸的坐标值 auto touchLocation = touch->getLocation(); //判断触摸位置是否超出屏幕 auto locationX = touchLocation.x; auto locationY = touchLocation.y; if (locationX <= s.width /2) { locationX = s.width / 2; } if (locationX >= winSize.width - s.width / 2) { locationX = winSize.width - s.width / 2; } if (locationY <= s.height / 2) { locationY = s.height / 2; } if (locationY >= winSize.height - s.height / 2) { locationY = winSize.height - s.height / 2; } // 点击范围判断检测 if (rect.containsPoint(locationInNode)) { log("touchX = %f, touchY = %f.", locationX, locationY); target->setPosition(Point(locationX, locationY)); //target->moveTo(touchLocation); } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(onTouchListener,hero); return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); sprite->runAction(MoveTo::create(3.0, Vec2(100, 100))); // add the sprite as a child to this layer this->addChild(sprite, 0); auto draw = DrawNode::create(); draw->drawDot(Vec2(visibleSize/2), 10.0f, Color4F::WHITE); this->addChild(draw); // イベントリスナー作成 auto listener = EventListenerTouchOneByOne::create(); // シングルタッチ // イベントを飲み込むかどうか listener->setSwallowTouches(true); // タッチ開始 listener->onTouchBegan = [](Touch* touch, Event* event){ // タッチ開始時の処理を書く auto location = touch->getLocation(); CCLOG("x=%f, y=%f", location.x, location.y); return true; }; // イベントリスナーを登録 this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); // 定期的に実行するタイマー this->schedule([](float dt){CCLOG("update");}, 5.0f, "Update"); // 一度だけ実行するタイマー this->scheduleOnce([](float dt){CCLOG("once");}, 3.0f, "Once"); return true; }
//启动摇杆(显示摇杆、监听摇杆触屏事件) void HRocker::startRocker(bool _isStopOther) { Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker); rocker->setVisible(true); Sprite *rockerBG = (Sprite *)this->getChildByTag(tag_rockerBG); rockerBG->setVisible(true); auto listenerTouch = EventListenerTouchOneByOne::create();//创建一个触摸监听 listenerTouch->setSwallowTouches(true);//设置是否想下传递触摸 //3.0 后可以直接在touchBegan后添加它的实现代码,而不用特意去写一个touchBegan的函数 listenerTouch->onTouchBegan = [=](Touch* touch, Event* event){ //[]中间的是传入的参数 CCPoint point = touch->getLocation(); Sprite *rocker = (Sprite *)this->getChildByTag(tag_rocker); if (rocker->boundingBox().containsPoint(point)) isCanMove = true; return true; }; //拖动精灵移动 listenerTouch->onTouchMoved = [this](Touch* touch, Event* event){ if (!isCanMove) { return; } CCPoint point = touch->getLocation(); Sprite *rocker = (Sprite *)this->getChildByTag(tag_rocker); //得到摇杆与触屏点所形成的角度 float angle = getRad(rockerBGPosition,point); //判断两个圆的圆心距是否大于摇杆背景的半径 if (sqrt(pow((rockerBGPosition.x - point.x),2) + pow((rockerBGPosition.y - point.y),2)) >= rockerBGR) { //保证内部小圆运动的长度限制 rocker->setPosition(ccpAdd(getAngelePosition(rockerBGR,angle),ccp(rockerBGPosition.x,rockerBGPosition.y))); } else { rocker->setPosition(point); } //判断方向 if(angle>=-PI/4&&angle<PI/4) { rocketDirection=rocker_right; rocketRun=false; } else if(angle>=PI/4&&angle<3*PI/4) { rocketDirection=rocker_up; } else if((angle>=3*PI/4&&angle<=PI)||(angle>=-PI&&angle<-3*PI/4)) { rocketDirection=rocker_left; rocketRun=true; } else if(angle>=-3*PI/4&&angle<-PI/4) { rocketDirection=rocker_down; } }; listenerTouch->onTouchEnded = [=](Touch* touch, Event* event){ // =在c++11里面代表这个lambda表达式中能使用外面的变量 // if (!isCanMove) // { // return; // } Sprite *rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG); Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker); rocker->stopAllActions(); rocker->runAction(CCMoveTo::create(0.08f,rockerBG->getPosition())); isCanMove = false; rocketDirection=rocker_stay; }; auto listenerKey = EventListenerKeyboard::create();//创建一个触摸监听 listenerKey->onKeyPressed = [this](EventKeyboard::KeyCode code, Event* event) { //isCanMove = true; switch(code) { case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: rocketDirection=rocker_right; rocketRun=false; break; case EventKeyboard::KeyCode::KEY_UP_ARROW: rocketDirection=rocker_up; break; case EventKeyboard::KeyCode::KEY_LEFT_ARROW: rocketDirection=rocker_left; rocketRun=true; break; case EventKeyboard::KeyCode::KEY_DOWN_ARROW: rocketDirection=rocker_down; break; default: break; } log("press key"); }; listenerKey->onKeyReleased = [this](EventKeyboard::KeyCode code, Event* event) { Sprite *rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG); Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker); rocker->stopAllActions(); rocker->runAction(CCMoveTo::create(0.08f,rockerBG->getPosition())); //isCanMove = false; rocketDirection=rocker_stay; log("released key"); }; //将触摸监听添加到eventDispacher中去 _eventDispatcher->addEventListenerWithSceneGraphPriority(listenerTouch ,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listenerKey ,this); }
void SportsLayer::Shieldtouched(){ //事件 auto listen=EventListenerTouchOneByOne::create(); listen->setSwallowTouches(true);//设置不想向下传递触摸 true是不想 默认为false listen->onTouchBegan = [this](Touch* touch, Event* event){ m_touchPoint = Director::getInstance()->convertToGL(touch->getLocationInView()); return true; }; listen->onTouchMoved = [this](Touch* touch, Event* event){ }; listen->onTouchEnded = [this](Touch* touch, Event* event){ Vec2 endPoint = Director::getInstance()->convertToGL(touch->getLocationInView()); if(endPoint.x>=this->getPositionX()-getContentSize().width/2&&endPoint.x<=this->getPositionX()+getContentSize().width/2){ float distance = endPoint.x - m_touchPoint.x; if (fabs(distance) > 50){ float width=Actual_x*0.8f; float hight=Actual_y*0.8f; if(vsion==1){ width=Actual_x*0.8f; hight=Actual_y*0.8f; }else if(vsion==2){ width=525; hight=450; } Size visibaleSize = Size(width,hight); if (distance < 0) { m_curPage++; }else{ m_curPage--; } if (m_curPage < 1) { m_curPage = 1; } if (m_curPage > 2) { m_curPage = 2; } Vec2 origin = Director::getInstance()->getVisibleOrigin(); Vec2 adjustPos =Vec2(origin.x - (m_curPage - 1) * visibaleSize.width,0); scrollView->setContentOffset(adjustPos,true); if(m_curPage>1){ jt1->setVisible(true); jt2->setVisible(false); if(vsion==2) b_label->setString(FX::StringsMap::getValue("dfljing")); }else if(m_curPage<2){ jt1->setVisible(false); jt2->setVisible(true); if(vsion==2) b_label->setString(FX::StringsMap::getValue("wdfzsm")); } } } }; EventDispatcher* dispatch=Director::getInstance()->getEventDispatcher(); dispatch->addEventListenerWithSceneGraphPriority(listen,this); // ignoreAnchorPointForPosition(false); setAnchorPoint(Vec2(0.5,0.5)); setPosition(Vec2(Actual_x/2,Actual_y/2)); setContentSize(Size(Actual_x,Actual_y)); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); mainLayer = Layer::create(); mainLayerParent = Layer::create(); postProcessingLayer = Layer::create(); uiLayer = Layer::create(); this->addChild(mainLayerParent); mainLayerParent->addChild(mainLayer); this->addChild(postProcessingLayer); this->addChild(uiLayer); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); auto switchItem = MenuItemImage::create( "switchuser.png", "switchuser.png", CC_CALLBACK_1(HelloWorld::switchCallback, this)); switchItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width - switchItem->getContentSize().width/2, origin.y + closeItem->getContentSize().height / 2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, switchItem, NULL); menu->setPosition(Point::ZERO); uiLayer->addChild(menu, 1); // shader 顯示 SpriteMask* pSprite2 = SpriteMask::create("wall_77.png"); pSprite2->setPosition(ccp(visibleSize.width / 2 - 90, visibleSize.height / 2)); mainLayer->addChild(pSprite2, 0); SpriteMask* pSprite3 = SpriteMask::create("wall_77.png"); pSprite3->setMask("wall0.png"); pSprite3->setPosition(ccp(visibleSize.width / 2 -30, visibleSize.height / 2)); mainLayer->addChild(pSprite3, 0); GrayMask* pSprite4 = GrayMask::create("wall_77.png"); pSprite4->setPosition(ccp(visibleSize.width / 2 + 30, visibleSize.height / 2)); mainLayer->addChild(pSprite4, 0); EdgeMask* pSprite5 = EdgeMask::create("wall_77.png"); pSprite5->setPosition(ccp(visibleSize.width / 2 + 90, visibleSize.height / 2)); mainLayer->addChild(pSprite5, 0); LightLayer *layer2 = LightLayer::create(); layer2->setTag(LAYER_SPOT); mainLayer->addChild(layer2, 0); DynamicBackground *layer3 = DynamicBackground::create(); layer3->setBackgroundPic(); mainLayer->addChild(layer3, -1); renderTexture = RenderTexture::create(visibleSize.width, visibleSize.height); renderTexture->retain(); mainLayerParent->setVisible(false); isPostProcessing = true; PostProcessing *test = PostProcessing::create(renderTexture->getSprite()->getTexture()); test->setFlippedY(true); //test->setScale(0.4f); postProcessingLayer->addChild(test); test->setPosition(Point(test->boundingBox().size.width/2, visibleSize.height - test->boundingBox().size.height / 2)); // Register Touch Event auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); this->scheduleUpdate(); return true; }
void FXDiskSprite::RegistListener() { first_rotation = 0.0; // Make sprite1 touchable auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); listener1->onTouchBegan = [&](Touch* touch, Event* event) { auto target = static_cast<Sprite*>(event->getCurrentTarget()); Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); //log("touched!"); log("sprite began... x = %f, y = %f", touch->getLocation().x, touch->getLocation().y); if (rect.containsPoint(locationInNode)) { //auto temp = static_cast<AudioTestScene*>(target->getParent()); first_x1 = touch->getLocation().x;//locationInNode.x; first_y1 = touch->getLocation().y;//locationInNode.y; first_rotation = target->getRotation();//((Sprite*)(target->getParent()->getChildByTag(100)))->getRotation(); //log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y); //target->setOpacity(180); return true; } return false; }; listener1->onTouchMoved = [&](Touch* touch, Event* event) { auto target = static_cast<Sprite*>(event->getCurrentTarget()); //target->setPosition(target->getPosition() + touch->getDelta()); //target->setRotation(); Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); move_x2 = touch->getLocation().x;//locationInNode.x; move_y2 = touch->getLocation().y;// locationInNode.y; //log("sprite move... x = %f, y = %f", touch->getLocation().x, touch->getLocation().y); Vec2 originV = Vec2(this->getPositionX(), this->getPositionY()); float x1 = first_x1; float y1 = first_y1; Vec2 p1 = Vec2(x1, y1) - originV; Vec2 p2 = Vec2(move_x2, move_y2) - originV; // float a = originV.getDistance(Vec2(first_x1, first_y1)); // float b = originV.getDistance(Vec2(move_x2, move_y2)); // float c = (Vec2(first_x1, first_y1)).getDistance(Vec2(move_x2, move_y2)); //float cosin = (a*a + b*b - c*c) / (2 * a*b); float angle = p2.getAngle(p1); //if (angle > 179.99) angle += 180; //if (angle < -179.99) angle -= 180; // float delta_x = first_x1 - move_x2; // float delta_y = first_y1 - move_x2; //log("sprite began... x = %f, y = %f , angle = %f", touch->getLocation().x, touch->getLocation().y, angle*180/3.1415); //((Sprite*)(target->getParent()->getChildByTag(100)))->setRotation(first_rotation + angle * 180.0 / 3.1415); target->setRotation(first_rotation + angle * 180.0 / 3.1415); }; listener1->onTouchEnded = [&](Touch* touch, Event* event) { auto target = static_cast<Sprite*>(event->getCurrentTarget()); }; listener1->retain(); (this->getParent())->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener1, this); }
bool TestController::init() { Layer::init(); Sprite *hello = Sprite::create("HelloWorld.png"); hello->setPosition(Vec2(240, 160)); this->addChild(hello); std::string text = std::string() + "Police have said they plan" + "to dismantle the camp of colorful" + "tents and art installations Thursday" + "morning, urging protesters to leave" + "peacefully."+ "On Thursday morning," + "bailiffs read out the court injunction," + "telling demonstrators to pack up and" + "leave on their own accord. They then" "began dismantling and removing barricades" "at the far western end of the protest area." + "The bailiffs carried off metal and plastic" + "barriers that had been lashed together, as" + "well as broken umbrellas -- wilted versions" + "of the protest movement's symbol."; textLabel = Label::createWithTTF(text, "fonts/Skranji-Regular.ttf", 24); textLabel->setAnchorPoint(Vec2(0, 1)); textLabel->setPosition(Vec2(0, 300)); textLabel->setDimensions(300, 500); textLabel->setAlignment(TextHAlignment::LEFT, TextVAlignment::TOP); // textLabel->enableOutline(Color4B(52, 26, 7, 255), 1); textLabel->enableShadow(Color4B(52, 26, 7, 255), Size(-0.5f, -0.5f)); // this->addChild(textLabel); CCLOG("content size = (%f, %f)", textLabel->getContentSize().width, textLabel->getContentSize().height); auto clipper = ClippingNode::create(); clipper->setTag( 98 ); clipper->setContentSize( Size(300, 300) ); clipper->setAnchorPoint( Vec2(0.5, 0.5) ); clipper->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2); // clipper->runAction(RepeatForever::create(RotateBy::create(1, 45))); this->addChild(clipper); auto stencil = DrawNode::create(); Vec2 rectangle[4]; rectangle[0] = Vec2(0, 0); rectangle[1] = Vec2(clipper->getContentSize().width, 0); rectangle[2] = Vec2(clipper->getContentSize().width, clipper->getContentSize().height); rectangle[3] = Vec2(0, clipper->getContentSize().height); Color4F white(1, 1, 1, 1); stencil->drawPolygon(rectangle, 4, white, 1, white); clipper->setStencil(stencil); // auto content = Sprite::create(); // content->setContentSize(Size(300, 300)); // content->setTag( 97 ); // content->setAnchorPoint( Vec2(0.5, 0.5) ); // content->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2); clipper->addChild(textLabel); // content->addChild(textLabel); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(TestController::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(TestController::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(TestController::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); rapidjson::Document json; std::string stdstr = std::string("{ \"hello\" : \"world\" }").c_str(); char str[2048]; sprintf(str, "%s", stdstr.c_str()); json.Parse<0>(str); const char key[] = "hello"; CCLOG("json value = %s", json[key].GetString()); return true; }
bool EndGameCustomModeNode::init() { if (!Node::init()) { return false; } Sprite* pBackground = Sprite::create("AdvanceMode/background.png"); pBackground->setPosition(Point(320.0f, 485.0f)); this->addChild(pBackground); auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); listener->setSwallowTouches(true); listener->onTouchBegan = [this](Touch* touch, Event* event) { return true; }; EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, pBackground); Sprite* pBackgroundPopUp = Sprite::create("AdvanceMode/panel-AM-short.png"); pBackgroundPopUp->setPosition(Point(320.0f, 595.0f)); this->addChild(pBackgroundPopUp); LabelBMFont *pLabelTitle = LabelBMFont::create("ADVANCE MODE", "fonts/font-bechic.fnt"); pLabelTitle->setAnchorPoint(Point(0.5f, 0.5f)); pLabelTitle->setPosition(Point(320.0f, 872.0f)); this->addChild(pLabelTitle); Sprite* pPanel = Sprite::create("AdvanceMode/panel-target-end-game.png"); pPanel->setPosition(Point(320.0f, 550.0f)); this->addChild(pPanel); /* Sprite* pIconEye1 = Sprite::create("AdvanceMode/eye-icon.png"); pIconEye1->setPosition(Point(500.0f, 550.0f)); this->addChild(pIconEye1); Sprite* pIconEye2 = Sprite::create("AdvanceMode/eye-icon.png"); pIconEye2->setPosition(Point(500.0f, 480.0f)); this->addChild(pIconEye2); */ m_csPackageInfo = CSPackageTable::getCSPackageInfo(m_sPackageId); if (m_csPackageInfo.iStage < m_iStage && m_iStage > 1) { Sprite* pNewRecord = Sprite::create("AdvanceMode/new-record.png"); pNewRecord->setPosition(Point(548.0f, 668.0f)); this->addChild(pNewRecord); m_csPackageInfo.iStage = m_iStage; } else if (m_csPackageInfo.iStage == 0) { m_csPackageInfo.iStage = m_iStage; } LabelBMFont *pLabelpackageName = LabelBMFont::create(m_csPackageInfo.sPackageName.c_str(), "fonts/font_title-popup.fnt"); pLabelpackageName->setAnchorPoint(Point(0.5f, 0.5f)); pLabelpackageName->setPosition(Point(320.0f, 780.0f)); this->addChild(pLabelpackageName); LabelTTF* pLabelTCreatedBy = LabelTTF::create(m_csPackageInfo.sCreatedBy.c_str(), "Arial", 28); pLabelTCreatedBy->setColor(ccc3(255.0f, 255.0f, 255.0f)); pLabelTCreatedBy->setPosition(Point(320.0f, 720.0f)); this->addChild(pLabelTCreatedBy); char sStage[20]; sprintf(sStage, "Stage %d", m_csPackageInfo.iStage); LabelBMFont *pLabelStage = LabelBMFont::create(sStage, "fonts/font_score.fnt", 310.0f); pLabelStage->setPosition(Point(320.0f, 630)); pLabelStage->setScale(1.4); this->addChild(pLabelStage); LabelBMFont *pLabelTotalWord = LabelBMFont::create("Total Words", "fonts/font_small_alert.fnt", 310.0f); pLabelTotalWord->setAnchorPoint(Point(0.0f, 0.5f)); pLabelTotalWord->setPosition(Point(122.0f, 550)); this->addChild(pLabelTotalWord); char sTotalWord[20]; sprintf(sTotalWord, "%d/%d", m_csPackageInfo.iTotalWordUnlock, m_csPackageInfo.iTotalWord); LabelBMFont *pLabelNumberTotalWord = LabelBMFont::create(sTotalWord, "fonts/font_score.fnt"); pLabelNumberTotalWord->setAnchorPoint(Point(1.0f, 0.5f)); pLabelNumberTotalWord->setPosition(Point(475.0f, 550)); pLabelNumberTotalWord->setScale(1.2); this->addChild(pLabelNumberTotalWord); LabelBMFont *pLabelWordNew = LabelBMFont::create("New words", "fonts/font_small_alert.fnt", 310.0f); pLabelWordNew->setAnchorPoint(Point(0.0f, 0.5f)); pLabelWordNew->setPosition(Point(122.0f, 480)); this->addChild(pLabelWordNew); char sTotalWordNew[10]; sprintf(sTotalWordNew, "%d", m_iWordNew); LabelBMFont *pLabelNumberWordNew = LabelBMFont::create(sTotalWordNew, "fonts/font_score.fnt"); pLabelNumberWordNew->setAnchorPoint(Point(1.0f, 0.5f)); pLabelNumberWordNew->setPosition(Point(475.0f, 480)); pLabelNumberWordNew->setScale(1.2); this->addChild(pLabelNumberWordNew); ButtonManagerNode* pButtonManagerNode = ButtonManagerNode::create(); this->addChild(pButtonManagerNode); Sprite* m_pButtonPlayImage = Sprite::create("AdvanceMode/btn_replay.png"); ButtonNode* pButtonPlay = ButtonNode::createButtonSprite(m_pButtonPlayImage, CC_CALLBACK_1(EndGameCustomModeNode::clickRetry, this)); pButtonPlay->setPosition(Point(320.0f, 345.0f)); pButtonManagerNode->addButtonNode(pButtonPlay); Sprite* m_pButtonCloseImage = Sprite::create("AdvanceMode/btn_close.png"); ButtonNode* pButtonClose = ButtonNode::createButtonSprite(m_pButtonCloseImage, CC_CALLBACK_1(EndGameCustomModeNode::clickClose, this)); pButtonClose->setPosition(Point(580.0f, 898.0f)); pButtonManagerNode->addButtonNode(pButtonClose); LeaderBoardAdvanceModeNode* pLeaderBoard = LeaderBoardAdvanceModeNode::createLayout(m_sPackageId); pLeaderBoard->setPosition(Point(320.0f, 114.0f)); this->addChild(pLeaderBoard); return true; }
bool MainGame::init() { CCLOG("game is begin."); auto size = Director::getInstance()->getWinSize(); auto sprite = Sprite::create("yellowstar.png"); sprite->setPosition(size.width/2, size.height/2); sprite->setTag(99); sprite->setAnchorPoint(Point(.5,.5)); this->addChild(sprite); /* it works auto node = DrawNode::create(); node -> setPosition(Point(0,0)); node -> setTag(100); this -> addChild(node); node -> drawSegment(Vec2(0,0),Vec2(sprite->getPositionX(), sprite->getPositionY()),0.6,Color4F::RED); */ this->schedule(schedule_selector(MainGame::gameLogic), 0.1); auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(MainGame::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(MainGame::onTouchEnded, this); /* it deprecated listener->onTouchBegan=[&](Touch * t,Event * e) { CCLOG("you touched me"); int realcol=t->getLocation().x/32; int realrow=t->getLocation().y/32; auto sprite = getChildByTag(99); int prevcol = sprite->getPosition().x /32; int prevrow = sprite->getPosition().y /32; int realcol=t->getLocation().x; int realrow=t->getLocation().y; auto sprite = this->getChildByTag(99); int prevcol = sprite->getPosition().x; int prevrow = sprite->getPosition().y; CCLOG("realcol:%D,prevcol:%D",realcol,prevcol); CCLOG("realrow:%D,prevrow:%D",realrow,prevrow); if (realcol < realrow) { this->moveDirection = ENUM_MOVEDIRECTION::emdLeft; CCLOG("you should go left"); } else { this->moveDirection = ENUM_MOVEDIRECTION::emdRight; CCLOG("you should go right"); } fail if (!kznode) { kznode = DrawNode::create(); } kznode -> setPosition(Vec2(realcol,realrow)); kznode -> setTag(100); kznode -> setAnchorPoint(Vec2(0, 0)); kznode -> drawSegment(Vec2(prevcol,prevrow),Vec2(realcol,realrow),0.6,Color4F::YELLOW); this->addChild(kznode); Vec2 kzfrom = Vec2(realcol,realrow); Vec2 kzto = Vec2(sprite->getPositionX(), sprite->getPositionY()); CCLOG("before:%f,%f",kzfrom.x,kzfrom.y); CCLOG("before:%f,%f",kzto.x,kzto.y); kzfrom = Director::getInstance()->convertToGL(kzfrom); //kzto = Director::getInstance()->convertToGL(kzto); //kzfrom = CCDirector(kzfrom); //kzto = convertToWorldSpaceAR(kzto); CCLOG("after:%f,%f",kzfrom.x,kzfrom.y); CCLOG("after:%f,%f",kzto.x,kzto.y); auto node = DrawNode::create(); node -> setPosition(Vec2(realcol,realrow)); node -> setTag(100); this -> addChild(node); node -> drawSegment(kzfrom,kzto,0.6,Color4F::BLUE); return true; }; */ _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; }
bool StartScene::init(){ if (!Layer::init()){return false;} OK = false; //必要な素材 Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //spriteの画像 Sprite *Sp1, *Sp2, *Sp3, *SpGo;//表示させるための画像を表示させる。 Sp1 = Sprite::create("1.png"); Sp1->setPosition(visibleSize / 2); Sp1->setRotation(180.0f); Sp1->setScale(0.0f); Sp2 = Sprite::create("2.png"); Sp2->setPosition(visibleSize / 2); Sp2->setRotation(180.0f); Sp2->setScale(0.0f); Sp3 = Sprite::create("3.png"); Sp3->setPosition(visibleSize / 2); Sp3->setRotation(180.0f); Sp3->setScale(0.0f); SpGo = Sprite::create("GO.png"); SpGo->setPosition(visibleSize / 2); SpGo->setRotation(180.0f); SpGo->setScale(0.0f); this->addChild(Sp1); this->addChild(Sp2); this->addChild(Sp3); this->addChild(SpGo); //動きに関するものを実行する auto big = ScaleTo::create(0.5f,0.7f); auto rot = RotateBy::create(0.5f,180.0f); auto bigrot = Spawn::create(big, rot, NULL); auto smole = ScaleTo::create(0.3f,0.0f); auto stop = DelayTime::create(0.5f); auto sequ = Sequence::create(bigrot,smole,NULL); //アクションを実行させる this->runAction(Sequence::create( TargetedAction::create(Sp3, sequ), TargetedAction::create(Sp2, sequ), TargetedAction::create(Sp1, sequ), TargetedAction::create(SpGo, sequ), CallFunc::create([this](){this->OK=true;}), nullptr )); auto lister = EventListenerTouchOneByOne::create(); lister->setSwallowTouches(true); lister->onTouchBegan = [](Touch*touch, Event*event)->bool{ return true; }; auto dis = Director::getInstance()->getEventDispatcher(); dis->addEventListenerWithSceneGraphPriority(lister, this); return true; }