void SimplePlatformerScene::onEnter() { BaseDemo::onEnter(); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(SimplePlatformerScene::onContactBegin, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); }
void LevelMenuScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *event){ if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 && keyCode == EventKeyboard::KeyCode::KEY_ESCAPE)) { getEventDispatcher()->removeEventListener(touchListener_); CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(); CocosDenshion::SimpleAudioEngine::getInstance()->stopAllEffects(); Director::getInstance()->pushScene(MainMenuScene::create(soundController_)->getScene()); } }
void Mecha::switchWeaponL() { _weaponLIndex++; if (_weaponLIndex >= sizeof(WEAPON_L_LIST) / sizeof(WEAPON_L_LIST[0])) { _weaponLIndex = 0; } auto weaponDisplay = (dragonBones::CCArmatureDisplay*)_weaponL->getDisplay(); weaponDisplay->getEventDispatcher()->removeCustomEventListeners(dragonBones::EventObject::FRAME_EVENT); const auto weaponName = WEAPON_L_LIST[_weaponLIndex]; _weaponL = CoreElementGame::instance->factory.buildArmature(weaponName); _armature->getSlot("weapon_l")->setChildArmature(_weaponL); weaponDisplay = (dragonBones::CCArmatureDisplay*)_weaponL->getDisplay(); weaponDisplay->getEventDispatcher()->setEnabled(true); weaponDisplay->getEventDispatcher()->addCustomEventListener(dragonBones::EventObject::FRAME_EVENT, std::bind(&Mecha::_frameEventHandler, this, std::placeholders::_1)); }
void BattleFieldUI::showVictoryUI() {//show the victory UI when win //diable AI //color layer auto layer = LayerColor::create(Color4B(10, 10, 10, 150)); layer->ignoreAnchorPointForPosition(false); layer->setPosition3D(Vec3(VisibleSize.width*0.5, VisibleSize.height*0.5, 0)); //add victory auto victory = Sprite::createWithSpriteFrameName("victory.png"); victory->setPosition3D(Vec3(VisibleSize.width*0.5, VisibleSize.height*0.5, 3)); victory->setScale(0.1); layer->addChild(victory, 1); layer->setGlobalZOrder(100); victory->setGlobalZOrder(100); //victory runaction auto action = EaseElasticOut::create(ScaleTo::create(1.5, 1)); victory->runAction(action); auto listener = EventListenerTouchOneByOne::create(); //touch event listener->onTouchBegan = [](Touch*, Event*) { return true; }; listener->onTouchEnded = [this](Touch*, Event*) { //clear GlobalVaribals HeroPool.clear(); DragonPool.clear(); SlimePool.clear(); RatPool.clear(); BossPool.clear(); PigletPool.clear(); HeroManager.clear(); MonsterManager.clear(); GameMaster::reset(); //stop schedule currentLayer->unscheduleUpdate(); Director::getInstance()->getScheduler()->unschedule("gameController", currentLayer); //stop sound experimental::AudioEngine::stop(AUDIO_ID.BATTLEFIELDBGM); //replace scene Director::getInstance()->replaceScene(ChooseRoleScene::createScene()); }; victory->setCameraMask(2); auto eventDispatcher = layer->getEventDispatcher(); eventDispatcher->addEventListenerWithSceneGraphPriority(listener, layer); addChild(layer); }
Hero::Hero() : _isJumping(false), _isAttacking(false), _hitCount(0), _weaponIndex(0), _weaponName(""), _weaponsLevel(), _faceDir(1), _moveDir(0), _speedX(0.f), _speedY(0.f), _armature(nullptr), _armatureDisplay(nullptr), _armArmature(nullptr) { WEAPON_LIST.push_back("sword"); WEAPON_LIST.push_back("pike"); WEAPON_LIST.push_back("axe"); WEAPON_LIST.push_back("bow"); _weaponName = WEAPON_LIST[_weaponIndex]; _weaponsLevel.resize(4, 0); _armature = KnightGame::instance->factory.buildArmature("knight"); _armatureDisplay = (dragonBones::CCArmatureDisplay*)_armature->getDisplay(); _armatureDisplay->setPosition(480.f, KnightGame::GROUND); _armatureDisplay->setScale(1.f); _armArmature = _armature->getSlot("armOutside")->getChildArmature(); const auto armArmatureDisplay = (dragonBones::CCArmatureDisplay*)_armArmature->getDisplay(); armArmatureDisplay->getEventDispatcher()->setEnabled(true); armArmatureDisplay->getEventDispatcher()->addCustomEventListener(dragonBones::EventObject::COMPLETE, std::bind(&Hero::_armEventHandler, this, std::placeholders::_1)); armArmatureDisplay->getEventDispatcher()->addCustomEventListener(dragonBones::EventObject::FRAME_EVENT, std::bind(&Hero::_armEventHandler, this, std::placeholders::_1)); _updateAnimation(); dragonBones::WorldClock::clock.add(_armature); KnightGame::instance->addChild(_armatureDisplay); }
void GameMap::addDialogueTouchEvent(std::vector<DialogueData> dialogue){ int dialogueMaxIndex = dialogue.size(); auto dialogueBg = dialogueManager->getDialogueBg(); //定义点击回调事件 onMapTouchBegan = [&, dialogue, dialogueBg, dialogueMaxIndex](Touch * touch, Event * unused_event){ if (GameMap::dialogueIndex >= dialogueMaxIndex){ //对话完毕 dialogueBg->getEventDispatcher()->removeEventListenersForTarget(dialogueBg);//关闭点击事件 dialogueManager->hideDialogue(); this->isShowDialogue = false; return true; } updateDialogueContent(dialogue); return true; }; EventListenerTouchOneByOne* listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = onMapTouchBegan; dialogueBg->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, dialogueBg); }
bool GameInfoScene::init() { if ( !Layer::init() ) { return false; } auto keyboard = EventListenerKeyboard::create(); keyboard->onKeyReleased = CC_CALLBACK_2(GameInfoScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboard, this); oldGems = GameSettings::Gems; schedule(schedule_selector(GameInfoScene::checkGemsChanged), 1.0f); return true; }
bool MainScene::init() { if ( !Layer::init() ) { return false; } _size = Director::getInstance()->getWinSize(); _xPosition = 0; _xMoved = 0; _touchListener = EventListenerTouchOneByOne::create(); _touchListener->onTouchBegan = CC_CALLBACK_2(MainScene::touchBegan,this); _touchListener->onTouchMoved = CC_CALLBACK_2(MainScene::touchMoved, this); _touchListener->onTouchEnded = CC_CALLBACK_2(MainScene::touchEnded,this); getEventDispatcher()->addEventListenerWithFixedPriority(_touchListener, 100); addScreen(1, new MainScreen); addScreen(2, new MainScreen); _fon = Sprite::create("img/ScreenFon.png"); _fon->setScaleX(_size.width/_fon->getContentSize().width); _fon->setScaleY(_size.height/_fon->getContentSize().height); _fon->setPosition(Point(_size.width/2, _size.height/2)); this->addChild(_fon,0); _menu = new MenuView; _menu->initialization(this); TextFieldTTF * tf = TextFieldTTF::textFieldWithPlaceHolder("click for input", "fonts/menuFont.otf", 26); tf->setPosition(Point(300,300)); this->addChild(tf, 10); tf->attachWithIME(); //this->schedule(schedule_selector(MainScene::update),0.05f); return true; }
bool PlayerPlane::initWithParent(cocos2d::Node * parent) { if (!parent) return false; bool ret = this->init(); auto director = Director::getInstance(); auto visibleSize = director->getVisibleSize(); Vec2 origin = director->getVisibleOrigin(); _rectVisible = Rect(origin.x, origin.y, visibleSize.width, visibleSize.height); parent->addChild(this); this->runAction(MoveTo::create(1.0f, Vec2(visibleSize.width/2, visibleSize.height/4))); // register touches event auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = [&](const std::vector<Touch*>& touches, Event *unused_event) { _bIsTouching = true; _vFigherPositionDelta = Vec2::ZERO; }; listener->onTouchesMoved = [&](const std::vector<Touch*>& touches, Event *unused_event) { if (_bIsTouching && !touches.empty()) _vFigherPositionDelta += touches.front()->getDelta(); }; listener->onTouchesEnded = [&](const std::vector<Touch*>& touches, Event *unused_event) { _bIsTouching = false; }; listener->onTouchesCancelled = [&](const std::vector<Touch*>& touches, Event *unused_event) { _bIsTouching = false; }; director->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, parent); scheduleUpdate(); return ret; }
void SightLightScene::setupNodes() { //添加背景图 auto visSize = Director::getInstance()->getVisibleSize(); auto background = Sprite::create("res/sightlight/background.png"); background->setPosition(0,0); background->setAnchorPoint(Vec2(0,0)); addChild(background,1); //创建两个DrawNode,一个用来画静态线段,一个画动态线段 _staticDraw = DrawNode::create(); addChild(_staticDraw,100); _touchDraw = DrawNode::create(); // addChild(_touchDraw,100); //创建ClippingNode,设置底板和模板 _clip = ClippingNode::create(); _clip->setInverted(false); _clip->setAlphaThreshold(255.0f); auto foreground = Sprite::create("res/sightlight/foreground.png"); foreground->setPosition(0,0); foreground->setAnchorPoint(Vec2(0,0)); _clip->addChild(foreground); _clip->setStencil(_touchDraw); addChild(_clip,101); //画线段,并保存所有不重复的端点 initSegments(); initPoints(); //触摸监听 auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [this](Touch *touch,Event* event) { this->onTouchMoved(touch, event); return true; }; listener->onTouchMoved = CC_CALLBACK_2(SightLightScene::onTouchMoved,this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); }
void HelloWorld::addLiseners() { auto director = Director::getInstance(); auto handler = [=](Touch * t, Event * e) { auto target = e->getCurrentTarget(); if (target->getBoundingBox().containsPoint(t->getLocation())) { if (aTf == target) { aTf->attachWithIME(); } else if (bTf == target) { bTf->attachWithIME(); } else if (target == addBtn) { int a = __String::create(aTf->getString())->intValue(); int b = __String::create(bTf->getString())->intValue(); resultLabel->setString(StringUtils::format("%d", a+b)); } } return false; }; auto addListenerToTarget = [director, handler](Node* target){ auto l = EventListenerTouchOneByOne::create(); l->onTouchBegan = handler; director->getEventDispatcher()->addEventListenerWithSceneGraphPriority(l, target); }; addListenerToTarget(addBtn); addListenerToTarget(aTf); addListenerToTarget(bTf); }
void GameLayer::setupLayout() { _vector_obstacles.clear(); _vector_game_object.clear(); _direction = kDirectionNone; _is_character_moving = false; _isTouching = false; _gameOver = false; _createWorld(); EventListenerTouchAllAtOnce* listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(GameLayer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(GameLayer::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(GameLayer::onTouchesEnded, this); listener->onTouchesCancelled = CC_CALLBACK_2(GameLayer::onTouchesCancelled, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); this->scheduleUpdate(); }
static VALUE scene_on_touch_event(VALUE rcv, SEL sel, mc_Scene_EventType type) { VALUE block = rb_current_block(); if (block == Qnil) { rb_raise(rb_eArgError, "block not given"); } block = rb_retain(block); // FIXME need release... auto scene = SCENE(rcv); if (scene->touch_listener == NULL) { scene->touch_listener = cocos2d::EventListenerTouchOneByOne::create(); } else { scene->getEventDispatcher()->removeEventListener(scene->touch_listener); } auto lambda = [block](cocos2d::Touch *touch, cocos2d::Event *event) -> bool { VALUE touch_obj = rb_class_wrap_new((void *)touch, rb_cTouch); return RTEST(rb_block_call(block, 1, &touch_obj)); }; switch (type) { case ON_BEGIN: scene->touch_listener->onTouchBegan = lambda; break; case ON_MOVE: scene->touch_listener->onTouchMoved = lambda; break; case ON_END: scene->touch_listener->onTouchEnded = lambda; break; case ON_CANCEL: scene->touch_listener->onTouchCancelled = lambda; break; } return scene_add_listener(rcv, scene->touch_listener); }
bool LevelMenuScene::TouchBegan(Touch *touch, Event *event) { int x = touch->getLocation().x; int y = touch->getLocation().y; rectangle_ = new PRectangle(x, y, 20, 20); nextPage(buttonArrowLeft_, 0); nextPage(buttonArrowRight_, LAST_PAGE); buttonArrowLeft_->show(page_, 0); buttonArrowRight_->show(page_, LAST_PAGE); for (int i = 0; i < levels_.size(); i++){ if (!levels_.at(i)->getLock() && levels_.at(i)->getRect()->intersects(rectangle_)){ getEventDispatcher()->removeEventListener(touchListener_); CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(); Director::getInstance()->pushScene(WorldScene::create(levels_.at(i)->getName(), i, soundController_)->getScene()); } } return true; }
void BaseSprite::__initEventListener() { auto eventListener = EventListenerTouchOneByOne::create(); eventListener->setSwallowTouches(true); eventListener->onTouchBegan = [](Touch *touch,Event *event)->bool{ auto target = static_cast<BaseSprite*>(event->getCurrentTarget()); auto locationNode = target->convertToNodeSpace(touch->getLocation()); auto size = target->getContentSize(); auto rect = Rect(0, 0, size.width, size.height); if (rect.containsPoint(locationNode)) { if(target->touchBeganHandler) { target->touchBeganHandler(target); } return true; } return false; }; eventListener->onTouchEnded = [](Touch *touch,Event *event)->void{ auto target = static_cast<BaseSprite*>(event->getCurrentTarget()); if(target->touchEndedHandler) { target->touchEndedHandler(target); } }; eventListener->onTouchMoved = [](Touch *touch,Event *event)->void{ auto target = static_cast<BaseSprite*>(event->getCurrentTarget()); if(target->touchMovedHandler) { target->touchMovedHandler(target); } }; getEventDispatcher()->addEventListenerWithSceneGraphPriority(eventListener, this); }
bool HomeScene::init(){ if (!Scene::init()){ return false; } SimpleAudioEngine::getInstance()->preloadEffect(Audio::RESTART_AUDIO.c_str()); SimpleAudioEngine::getInstance()->preloadEffect(Audio::DIG_AUDIO.c_str()); SimpleAudioEngine::getInstance()->preloadEffect(Audio::MINE1_AUDIO.c_str()); SimpleAudioEngine::getInstance()->preloadEffect(Audio::BUTTON.c_str()); SimpleAudioEngine::getInstance()->preloadEffect(Audio::FAIL_AUDIO.c_str()); SimpleAudioEngine::getInstance()->preloadEffect(Audio::CRASH_AUDIO.c_str()); Sprite *BG = Sprite::create("background.jpg"); BG->setPosition(VISIZE.width / 2, VISIZE.height / 2); BG->setScaleX(VISIZE.width / BG->getContentSize().width); BG->setScaleY(VISIZE.height / BG->getContentSize().height); this->addChild(BG,0); c2 = Sprite::create("cloud2.png"); c2->setPosition(VISIZE.width * 0.2, VISIZE.height * 0.4); c2->setScale(VISIZE.width / c2->getContentSize().width); this->addChild(c2,2); Sprite *star = Sprite::create("Brick.jpg"); star->setPosition(VISIZE.width / 2, VISIZE.height / 2); star->setScaleX(VISIZE.width / star->getContentSize().width); star->setScaleY(VISIZE.height / star->getContentSize().height); this->addChild(star,3); dig_logo = Sprite::create("dig_logo.png"); dig_logo->setPosition(VISIZE.width/2,VISIZE.height*0.6); dig_logo->setScale(VISIZE.width/dig_logo->getBoundingBox().size.width); this->addChild(dig_logo,4); auto playMenu = Sprite::create("pl.png"); playMenu->runAction(MoveBy::create(0.5,Point(0,-playMenu->getBoundingBox().size.height/2))); playMenu->setPosition(dig_logo->getContentSize().width/2,dig_logo->getContentSize().height/2); dig_logo->addChild(playMenu); auto listenner = EventListenerTouchOneByOne::create(); listenner->onTouchBegan = [=](Touch* touch,Event* event){ if(playMenu->getBoundingBox().containsPoint(playMenu->getParent()->convertToNodeSpace(touch->getLocation()))){ playMenu->setScale(playMenu->getScale()*1.2); isOut = false; log("ok"); return true; } return false; }; listenner->onTouchMoved = [=](Touch* touch,Event* event){ if(playMenu->getBoundingBox().containsPoint(playMenu->convertToNodeSpace(touch->getLocation()))){ isOut = true; } else{ isOut = false; } }; listenner->onTouchEnded = [=](Touch* touch,Event* event){ if(!isOut){ int beforeReplpace = 0.5; playMenu->setScale(playMenu->getScale()/1.2); dig_logo->runAction(EaseBackOut::create(MoveTo::create(beforeReplpace,Point(VISIZE.width/2,VISIZE.height*1.5)))); playMenu->runAction(Sequence::create(EaseBackOut::create(MoveBy::create(beforeReplpace,Point(0,0))), CallFunc::create([=](){ //this->runAction(RuduceVolume::create(0.3)); Director::getInstance()->replaceScene(TransitionSlideInB::create(0.3,DigScene::createScene())); }), nullptr)); } }; playMenu->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listenner,dig_logo); return true; }
/////////////////////////BLOB LAYER bool BlobLayer::init() { if (!Layer::init()) return false; Entity::Game = this; setContentSize(Size(DESIGN_X, DESIGN_Y)); b2Vec2 gravity; gravity.Set(0.0f, -10.0f); world = new b2World(gravity); world->SetContinuousPhysics(true); world->SetContactListener(this); // Create edges around the entire screen // Define the ground body. b2BodyDef groundBodyDef; groundBodyDef.position.Set(0, 0); // bottom-left corner // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). // The body is also added to the world. auto _groundBody = world->CreateBody(&groundBodyDef); // Define the ground box shape. b2EdgeShape groundBox; // bottom groundBox.Set(b2Vec2(0, 0), b2Vec2(DESIGN_X / PTM_RATIO, 0)); _groundBody->CreateFixture(&groundBox, 0); // top //groundBox.Set(b2Vec2(0, DESIGN_Y / PTM_RATIO), b2Vec2(DESIGN_X / PTM_RATIO, DESIGN_Y / PTM_RATIO)); //_groundBody->CreateFixture(&groundBox, 0); // left groundBox.Set(b2Vec2(0, DESIGN_Y * 1.1f / PTM_RATIO), b2Vec2(0, 0)); _groundBody->CreateFixture(&groundBox, 0); // right groundBox.Set(b2Vec2(DESIGN_X / PTM_RATIO, 0), b2Vec2(DESIGN_X / PTM_RATIO, DESIGN_Y * 1.1f / PTM_RATIO)); _groundBody->CreateFixture(&groundBox, 0); state = GameStates::Playing; scheduleUpdate(); //schedule(schedule_selector(BlobLayer::generate), 2.3f); bigText = Label::createWithTTF("", NORMAL_TTF, 200.0f); bigText->setHorizontalAlignment(TextHAlignment::CENTER); bigText->setVerticalAlignment(TextVAlignment::CENTER); bigText->setPosition(CP(0.5f, 0.45f)); addChild(bigText, 10); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(BlobLayer::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(BlobLayer::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(BlobLayer::onTouchEnded, this); touchListener->onTouchCancelled = CC_CALLBACK_2(BlobLayer::onTouchEnded, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this); auto tilt = EventListenerAcceleration::create(CC_CALLBACK_2(BlobLayer::onAcceleration, this)); getEventDispatcher()->addEventListenerWithSceneGraphPriority(tilt, this); ambientForce = b2Vec2_zero; regenPeriod = 1.5f; minRegenPeriod = regenPeriod * 0.5f; regenTime = 0; lastObservedScore = BlobScene::LastScore; schedule(schedule_selector(BlobLayer::checkCombo), 1.5f); /* auto ringParticle = ParticleGalaxy::create(); ringParticle->setPositionType(ParticleSystem::PositionType::RELATIVE); ring->addChild(ringParticle);*/ return true; }
int PlayerWin::run() { FileUtils::getInstance()->setPopupNotify(false); INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); // set QUICK_V3_ROOT const char *QUICK_V3_ROOT = getenv("QUICK_V3_ROOT"); if (!QUICK_V3_ROOT || strlen(QUICK_V3_ROOT) == 0) { MessageBox("Please run \"setup_win.bat\", set Quick-Cocos2dx-Community root path.", "Quick-Cocos2dx-Community player error"); return 1; } _project.setQuickCocos2dxRootPath(QUICK_V3_ROOT); // load project config from command line args vector<string> args; for (int i = 0; i < __argc; ++i) { wstring ws(__wargv[i]); string s; s.assign(ws.begin(), ws.end()); args.push_back(s); } _project.parseCommandLine(args); if (_project.getProjectDir().empty()) { if (args.size() >= 2) { // for Code IDE before RC2 _project.setProjectDir(args.at(1)); } else { _project.resetToWelcome(); } } // set framework path if (!_project.isLoadPrecompiledFramework()) { FileUtils::getInstance()->addSearchPath(_project.getQuickCocos2dxRootPath() + "quick/"); } // create the application instance _app = new AppDelegate(); _app->setProjectConfig(_project); // set window icon HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PLAYER)); // create console window if (_project.isShowConsole()) { AllocConsole(); _hwndConsole = GetConsoleWindow(); if (_hwndConsole != NULL) { SendMessage(_hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon); SendMessage(_hwndConsole, WM_SETICON, ICON_SMALL, (LPARAM)icon); ShowWindow(_hwndConsole, SW_SHOW); BringWindowToTop(_hwndConsole); freopen("CONOUT$", "wt", stdout); freopen("CONOUT$", "wt", stderr); HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE); if (hmenu != NULL) { DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND); } } } // log file if (_project.isWriteDebugLogToFile()) { const string debugLogFilePath = _project.getDebugLogFilePath(); _writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w"); if (!_writeDebugLogFile) { CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str()); } } // set environments SetCurrentDirectoryA(_project.getProjectDir().c_str()); FileUtils::getInstance()->setSearchRootPath(_project.getProjectDir().c_str()); FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str()); // check screen DPI HDC screen = GetDC(0); int dpi = GetDeviceCaps(screen, LOGPIXELSX); ReleaseDC(0, screen); // set scale with DPI // 96 DPI = 100 % scaling // 120 DPI = 125 % scaling // 144 DPI = 150 % scaling // 192 DPI = 200 % scaling // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor // // enable DPI-Aware with DeclareDPIAware.manifest // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness float screenScale = 1.0f; //if (dpi >= 120 && dpi < 144) //{ // screenScale = 1.25f; //} //else if (dpi >= 144 && dpi < 192) //{ // screenScale = 1.5f; //} //else if (dpi >= 192) //{ // screenScale = 2.0f; //} CCLOG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale); // create opengl view Size frameSize = _project.getFrameSize(); float frameScale = 1.0f; if (_project.isRetinaDisplay()) { frameSize.width *= screenScale; frameSize.height *= screenScale; } else { frameScale = screenScale; } const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height); const bool isResize = _project.isResizeWindow(); GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); //auto glview = GLView::createWithRect("Quick-Cocos2dx-Community", frameRect, frameScale, isResize, false, true); auto glview = GLViewImpl::createWithRect("Quick-Cocos2dx-Community", frameRect, frameScale); _hwnd = glview->getWin32Window(); SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon); SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon); FreeResource(icon); auto director = Director::getInstance(); director->setOpenGLView(glview); // set window position if (_project.getProjectDir().length()) { setZoom(_project.getFrameScale()); } Vec2 pos = _project.getWindowOffset(); if (pos.x != 0 && pos.y != 0) { RECT rect; GetWindowRect(_hwnd, &rect); MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE); } // init player services initServices(); loadLuaConfig(); registerKeyboardEvent(); // register event handlers auto eventDispatcher = director->getEventDispatcher(); eventDispatcher->addCustomEventListener("APP.WINDOW_CLOSE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowClose, this)); eventDispatcher->addCustomEventListener("APP.WINDOW_RESIZE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowResize, this)); eventDispatcher->addCustomEventListener("APP.VIEW_SCALE", CC_CALLBACK_1(PlayerWin::onWindowScale, this)); // prepare _project.dump(); auto app = Application::getInstance(); g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWL_WNDPROC, (LONG)PlayerWin::windowProc); HWND hwnd = _hwnd; HWND hwndConsole = _hwndConsole; const ProjectConfig &project = _project; director->getScheduler()->schedule([hwnd, hwndConsole, project](float dt) { CC_UNUSED_PARAM(dt); ShowWindow(hwnd, SW_RESTORE); auto glview = dynamic_cast<GLViewImpl*>(Director::getInstance()->getOpenGLView()); GLFWwindow *window = glview->getWindow(); glfwShowWindow(window); }, this, 0.0f, 0, 0.001f, false, "SHOW_WINDOW_CALLBACK"); if (project.isAppMenu() && GetMenu(hwnd)) { // update window size RECT rect; GetWindowRect(_hwnd, &rect); MoveWindow(_hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top + GetSystemMetrics(SM_CYMENU), FALSE); } ShowWindow(_hwnd, SW_MINIMIZE); // startup message loop return app->run(); }
bool GameScene::init(){ if (!Layer::init()) { return false; } //获取场景 范围 尺寸数值 auto origin= Director::getInstance()->getVisibleOrigin(); auto visibleSize= Director::getInstance()->getVisibleSize(); float xScale; float yScale; //加载精灵帧缓存 SpriteFrameCache::getInstance()->addSpriteFramesWithFile("images/game.plist"); //添加背景(BG) auto gameBG= Sprite::createWithSpriteFrameName("bg.png"); xScale= visibleSize.width/gameBG->getContentSize().width; yScale= visibleSize.height/gameBG->getContentSize().height; gameBG->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); gameBG->setScale(xScale, yScale); addChild(gameBG); //添加陆地 auto land = Land::create(); land->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); land->setPosition(Point::ZERO); this->addChild(land,2); //添加小鸟 bird = SpriteBird::create(); bird->setPosition(Point(100,100)); addChild(bird,2); bird->changeState(ACTION_STATE_IDLE); auto ball =Sprite_Ball::create(); ball->setPosition(Point(visibleSize.width/2,100)); addChild(ball,3); //创建点击监听 auto touchListener= EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(false); touchListener->onTouchBegan = [=](Touch * t, Event * e){ return true; }; touchListener->onTouchEnded = [=](Touch * t, Event * e){ startGame(); //添加障碍水管 pipe = Pipe::create(); this->addChild(pipe); //移除所有监听 ?? _eventDispatcher->removeEventListener(touchListener); }; getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this); //创建碰撞监听 contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = [=](const PhysicsContact & contact){ //停止所有动作 land->landStop(); pipe->stopePipe(); bird->changeState(ACTION_STATE_DIE); _eventDispatcher->removeEventListener(contactListener); return true; }; getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }
// this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { auto director = Director::getInstance(); director->startAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); }
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { auto director = Director::getInstance(); director->stopAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); }
void KeyboardManager::createUpdateListener() { auto updateListener = EventListenerCustom::create(Director::EVENT_AFTER_UPDATE, CC_CALLBACK_1(KeyboardManager::onKeyUpdate, this)); getEventDispatcher()->addEventListenerWithSceneGraphPriority(updateListener, this); }
bool EpisodeLockedScene::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); addChild(BackgroundWidget::create("bg" + nToString(GameSettings::CurrentEpisode), Color3B(200, 200, 200))); addChild(Vignette::create()); auto hole = MAKESPRITE("blackholebig"); addChild(hole); hole->setPosition(CP(0.5f, 0.65f)); hole->setScale(0.8f); hole->runAction(RepeatForever::create(RotateBy::create(40.0, 365))); auto gamelogo = MAKESPRITE("gamelogo"); addChild(gamelogo); gamelogo->setPosition(CP(0.5f, 0.65f)); gamelogo->setScale(0.8f); gamelogo->runAction(RepeatForever::create(Sequence::createWithTwoActions( ScaleTo::create(3.0f, 0.81f), ScaleTo::create(3.0f, 0.79f) ))); string title = LS(EpisodeInfos[GameSettings::CurrentEpisode].title); int price = EpisodeInfos[GameSettings::CurrentEpisode].price; auto hooker = TopAnchor::create(); addChild(hooker, 1); auto hookerMenu = Menu::create(); hookerMenu->setPosition(Point::ZERO); hooker->addChild(hookerMenu); #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) auto btnMenu = MAKEBUTTON("btnBackUp", "btnBackDn", EpisodeLockedScene::menuCloseCallback); btnMenu->setPosition(VCP(0.03f, 0.95f)); btnMenu->setAnchorPoint(Point(0, 1.0f)); btnMenu->setScale(1.3f); hookerMenu->addChild(btnMenu); #endif auto pMenu = Menu::create(); pMenu->setPosition(Point::ZERO); addChild(pMenu, 1); auto episodetext = Label::createWithTTF(LS("Episode") + " " + nToString(GameSettings::CurrentEpisode + 1), FANCY_TTF, 50.0f); episodetext->setHorizontalAlignment(TextHAlignment::CENTER); episodetext->setPosition(VCP(0.5f, 0.45f)); addChild(episodetext); auto episodetitle = Label::createWithTTF(title, FANCY_TTF, 60.0f); episodetitle->setHorizontalAlignment(TextHAlignment::CENTER); episodetitle->setPosition(VCP(0.5f, 0.38f)); addChild(episodetitle); string unlocktextstring = LS("UnlockEpisodeMessageWithProgress"); auto unlocktext = Label::createWithTTF(string_format(unlocktextstring, price), FANCY_TTF, 38.0f); unlocktext->setHorizontalAlignment(TextHAlignment::CENTER); unlocktext->setPosition(VCP(0.5f, 0.25f)); addChild(unlocktext); auto keyboard = EventListenerKeyboard::create(); keyboard->onKeyReleased = CC_CALLBACK_2(EpisodeLockedScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboard, this); return true; }
// on "init" you need to initialize your instance bool GamePlaying::init() { _trans=false; _tag=0; ////////////////////////////// // 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(GamePlaying::menuCloseCallback, this)); Vec2 menupos = Vec2(origin.x + visibleSize.width, origin.y + closeItem->getContentSize().height/2); menupos.x -=closeItem->getContentSize().width/2; closeItem->setPosition(menupos); //リロード auto reloadItem = MenuItemImage::create( "reload.png", "reload.png", CC_CALLBACK_1(GamePlaying::menuReloadCallback, this)); menupos.x =visibleSize.width/2; reloadItem->setPosition(menupos); //次へ auto nextItem = MenuItemImage::create( "next.png", "next.png", CC_CALLBACK_1(GamePlaying::menuNextCallback, this)); menupos.x =visibleSize.width/2 + nextItem->getContentSize().width*2; nextItem->setPosition(menupos); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, reloadItem ,nextItem, nullptr); menu->setPosition(Vec2::ZERO); this->addChild(menu, 100); int priority=0; _pm = PHYSICSSHAPE_MATERIAL_DEFAULT; _pm.friction = 0.5f; _pm.density = 0.5f; ///////////////////////////// // 3. add your codes below... //背景 auto bg = SpriteBatchNode::create("bg.png"); auto bg2 = SpriteBatchNode::create("bg2.png"); int i=0,j=0; for(int j=0;j<4;++j){ for(int i=0;i<2;++i){ auto sp=Sprite::createWithTexture(bg->getTexture()); sp->setPosition(128+i*256,128+j*256); bg->addChild(sp); auto sp2=Sprite::createWithTexture(bg2->getTexture()); sp2->setPosition(128+i*256,128+j*256); bg2->addChild(sp2); sp2->runAction(RepeatForever::create(Sequence::createWithTwoActions( FadeIn::create(2.5f),FadeOut::create(2.5f) ))); } } addChild(bg); addChild(bg2); TMXTiledMap* tiledmap; TMXMapInfo* mapinfo; if(stage_no==0){ _slushLimit=10; auto label = LabelTTF::create(GetUTF8FromSJIS("チャンスは1度きり…"), "Arial", 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, priority++); tiledmap = TMXTiledMap::create("stage1.tmx"); mapinfo = TMXMapInfo::create("stage1.tmx"); }else if(stage_no==2){ _slushLimit=2; auto label = LabelTTF::create(GetUTF8FromSJIS("チャンスは2回のみだ"), "Arial", 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, priority++); tiledmap = TMXTiledMap::create("stage2.tmx"); mapinfo = TMXMapInfo::create("stage2.tmx"); }else if(stage_no==2){ _slushLimit=3; #ifdef _WINDOWS auto label = LabelTTF::create(GetUTF8FromSJIS("3回切ってくれたまえ"), "Arial", 24); #else auto label = LabelTTF::create(GetUTF8FromSJIS("3回切ってくれたまえ"),"Arial",24); #endif // 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, priority++); tiledmap = TMXTiledMap::create("stage3.tmx"); mapinfo = TMXMapInfo::create("stage3.tmx"); }else{ _slushLimit=3; auto data = cocos2d::FileUtils::sharedFileUtils()->getStringFromFile("String.txt"); auto label = LabelTTF::create(data.c_str()/*("3回ぶった斬れ!!")*/, "MS Pゴシック", 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, priority++); tiledmap = TMXTiledMap::create("stage4.tmx"); mapinfo = TMXMapInfo::create("stage4.tmx"); } auto soni=Sprite::create("soniko_t.png"); soni->setScale(0.5); soni->setPosition(250,400); addChild(soni); Vector<TMXTilesetInfo*>& tileset = mapinfo->getTilesets(); TMXTilesetInfo* ts= tileset.at(0); ObjectLayerParse(tiledmap->getObjectGroup("cuttable"),priority); ObjectLayerParse(tiledmap->getObjectGroup("scaffold"),priority); auto director = Director::getInstance(); auto listener=EventListenerTouchOneByOne::create(); listener->onTouchBegan=CC_CALLBACK_2(GamePlaying::onTouchBegan,this); listener->onTouchMoved=CC_CALLBACK_2(GamePlaying::onTouchMoved,this); listener->onTouchEnded=CC_CALLBACK_2(GamePlaying::onTouchEnded,this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this); Director::getInstance()->getTextureCache()->addImage("blade.png"); auto qp=ParticleSystemQuad::create("hellfire.plist"); qp->setPosition(300,0); addChild(qp,10); //auto streak = MotionStreak::create(0.3f,0.01f,30.f,Color3B::WHITE,"trail.png"); //streak->setName("streak"); //streak->setBlendFunc(BlendFunc::ALPHA_PREMULTIPLIED); //addChild(streak); //streak->setBlendFunc(b); //cocos2d::BlendFunc b; //b.dst=GL_ZERO; //b.src=GL_ONE_MINUS_DST_COLOR; // //auto s=Sprite::create(); //s->setTextureRect(Rect(0,0,480,800)); //s->setPosition(240,400); //s->setColor(Color3B::WHITE); //s->setBlendFunc(b); //s->setName("reverse"); //s->setVisible(false); //addChild(s,65535); scheduleUpdate(); return true; }
// on "init" you need to initialize your instance bool ChooserScene::init(int _offset) { offset = _offset; ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); string title = vector < string > { "Moon", "Mars", "Uranus" }[GameSettings::CurrentEpisode]; auto hooker = TopAnchor::create(); addChild(hooker, 1); auto episodetitle = Label::createWithTTF(title, FANCY_TTF, 60.0f); episodetitle->setHorizontalAlignment(TextHAlignment::CENTER); episodetitle->setPosition(VCP(0.5f, 0.9f)); hooker->addChild(episodetitle); auto pMenu = Menu::create(); pMenu->setPosition(Point::ZERO); hooker->addChild(pMenu, 1); auto btnMenu = MAKEBUTTON("btnMenuUp", "btnMenuDn", ChooserScene::btnMenuPressed); btnMenu->setPosition(VCP(0, 1)); btnMenu->setAnchorPoint(Point(-0.5, 1.5)); btnMenu->setScale(1.3f); pMenu->addChild(btnMenu); auto pLevels = Menu::create(); pLevels->setPosition(Point::ZERO); pLevels->setTag(0); hooker->addChild(pLevels); const float startX = 0.2f; const float startY = 0.25f; auto bSprite = Sprite::createWithSpriteFrameName("circle"); auto contentsize = bSprite->getContentSize(); float off = 1.0f - (2.0f * startX); off /= (float) (lCount - 1); float offy = 1.0f - (startY * 2.0f); offy /= (float) (rCount - 1); log("Unlocked Level ID:" + nToString(GameSettings::GetUnlockedLevelId())); float y = startY; GLubyte cR = 255; for (int r = 0; r < rCount; r++) { float x = startX; GLubyte cG = 200; // static_cast<GLubyte>(200.0f * (float) offset / (float) GameSettings::MaximumLevelId); GLubyte cB = 20; // +200 - static_cast<GLubyte>(200.0f * (float) offset / (float) GameSettings::MaximumLevelId);; for (int i = 0; i < lCount; i++) { int levelId = offset + (rCount - (r + 1)) * lCount + i; if (levelId >= GameSettings::GetMaximumLevelId()) break; Node* btn; if (levelId <= GameSettings::GetUnlockedLevelId()) { btn = MAKEBUTTON("circle", "circleDn", ChooserScene::btnLevelPressed); btn->setTag(100 + levelId); pLevels->addChild(btn); blobs.push_back(btn); btn->setPosition(VCP(x, y)); Label* lbl = Label::createWithSystemFont(nToString(levelId + 1).c_str(), "Consolas", 28.0); lbl->setColor(Color3B::WHITE); lbl->setPosition(VCP(x, y)); numbers.push_back(lbl); this->addChild(lbl, 1); btn->setColor(Color3B(cR, cG, cB)); } else { btn = Sprite::createWithSpriteFrameName("circleLk"); btn->setTag(100 + levelId); hooker->addChild(btn); blobs.push_back(btn); btn->setPosition(VCP(x, y)); } btn->setScale(0.8f); #if ENABLE_IAD //btn->setScale(0.8f); #endif cG *= 0.5; cB *= 1.7; cB = cB > 255 ? 255 : cB; x += off; } cR *= 0.7; y += offy; } if (offset > 0) { auto backBtn = MAKEBUTTON("btnBackUp", "btnBackDn", btnBackPressed); backBtn->setPosition(CP(0.1f, 0.1f)); backBtn->setScale(1.3f); pMenu->addChild(backBtn); } if (offset + lCount * rCount < GameSettings::GetMaximumLevelId()) { auto nextBtn = MAKEBUTTON("btnNextUp", "btnNextDn", btnNextPressed); nextBtn->setPosition(CP(0.9f, 0.1f)); nextBtn->setScale(1.3f); pMenu->addChild(nextBtn); } schedule(schedule_selector(ChooserScene::bloop), 2.0f, kRepeatForever, 4.0f); auto keyboard = EventListenerKeyboard::create(); keyboard->onKeyReleased = CC_CALLBACK_2(ChooserScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboard, this); return true; }
bool WorldScene::init(std::string levelName, int currentLevel, SoundController* soundController) { if ( !Layer::init() ) { return false; } soundController_ = soundController; worldController_ = new WorldController(); size_ = Director::getInstance()->getWinSize(); worldLayer_ = Layer::create(); this->addChild(worldLayer_); positionX_ = 0; positionY_ = 0; isSound_ = UserDefault::getInstance()->getBoolForKey("SOUND", false); worldController_->setRecord(UserDefault::getInstance()->getIntegerForKey(levelName.c_str(), 0)); if(isSound_){ soundController_->preloadingAndPlayMusic(ESounds::ES_SIREN_SOUND, true); } worldController_->setDirection(LEFT); isPause_ = false; readLevel_ = new ReadLevel(); readLevel_->readFile(levelName); world_ = new World(readLevel_->getLevel(), soundController_); world_->setCurrentLevel(currentLevel); worldController_->init(world_, soundController_); touchListener_ = EventListenerTouchOneByOne::create(); touchListener_->onTouchBegan = CC_CALLBACK_2(WorldScene::TouchBegan,this); touchListener_->onTouchMoved = CC_CALLBACK_2(WorldScene::TouchMoved, this); touchListener_->onTouchEnded = CC_CALLBACK_2(WorldScene::TouchEnded,this); getEventDispatcher()->addEventListenerWithFixedPriority(touchListener_, 100); keyboardListener_ = EventListenerKeyboard::create(); keyboardListener_->onKeyReleased = CC_CALLBACK_2(WorldScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener_, this); for(auto brick: readLevel_->getLevel()->getBricks()){ worldLayer_->addChild(brick->getTexture(), 0); } this->addChild(worldController_->getLabelRecord(), 1); this->addChild(worldController_->getLabelScore(), 1); worldLayer_->addChild(world_->getPlayer()->getTexture(), 2); for(auto spirit: world_->getSpirits()){ worldLayer_->addChild(spirit->getTexture(), 2); } this->schedule(schedule_selector(WorldScene::updatePlayer),0.06f); this->schedule(schedule_selector(WorldScene::updateWorld),0.07f); this->schedule(schedule_selector(WorldScene::timerTask),1.0f); this->schedule(schedule_selector(WorldScene::speedTask),0.03f); this->schedule(schedule_selector(WorldScene::generateFruit), 15.0f); scene_ = Scene::create(); scene_->addChild(this); return true; }
void GetUnitScene::removeEventTapAfterAnimation() { getEventDispatcher()->removeCustomEventListeners(GatchaResultLayer::EventNameTapAfterAnimation); }
void BattleFieldUI::showGameOverUI() {//show the gameover UI when loss //diable AI //color layer auto layer = LayerColor::create(Color4B(255, 10, 10, 150)); layer->ignoreAnchorPointForPosition(false); layer->setPosition3D(Vec3(VisibleSize.width*0.5, VisibleSize.height*0.5, 0)); //add gameover auto gameOver = Sprite::create("battlefieldUI/gameover.png"); gameOver->setPosition3D(Vec3(VisibleSize.width*0.5, VisibleSize.height*0.5, 3)); gameOver->setScale(0.001); layer->addChild(gameOver, 1); layer->setGlobalZOrder(100); gameOver->setGlobalZOrder(100); auto listener = EventListenerTouchOneByOne::create(); //touch event listener->onTouchBegan = [](Touch*, Event*) { return true; }; listener->onTouchEnded = [this](Touch*, Event*) { //clear GlobalVaribals HeroPool.clear(); DragonPool.clear(); SlimePool.clear(); RatPool.clear(); BossPool.clear(); PigletPool.clear(); HeroManager.clear(); MonsterManager.clear(); GameMaster::reset(); //stop schedule currentLayer->unscheduleUpdate(); Director::getInstance()->getScheduler()->unschedule("gameController", currentLayer); //stop sound experimental::AudioEngine::stop(AUDIO_ID.BATTLEFIELDBGM); //replace scene Director::getInstance()->replaceScene(ChooseRoleScene::createScene()); }; gameOver->setCameraMask(2); auto eventDispatcher = layer->getEventDispatcher(); eventDispatcher->addEventListenerWithSceneGraphPriority(listener, layer); listener->setEnabled(false); auto enableListener = [=]() { listener->setEnabled(true); experimental::AudioEngine::stopAll(); experimental::AudioEngine::play2d("audios/effects/gameover.mp3"); }; //runaction auto action = Sequence::create(DelayTime::create(3), EaseElasticOut::create(ScaleTo::create(1.5, 1)), CallFunc::create(enableListener),NULL); gameOver->runAction(action); addChild(layer); }
bool HelpScene::init() { if ( !Layer::init() ) { return false; } touched = false; Size visibleSize = Director::getInstance()->getVisibleSize(); //setKeyboardEnabled(true); auto keyboard = EventListenerKeyboard::create(); keyboard->onKeyReleased = CC_CALLBACK_2(HelpScene::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboard, this); //setTouchEnabled(true); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(HelpScene::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(HelpScene::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(HelpScene::onTouchEnded, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); addChild(BackgroundWidget::create("bg", Color3B(20, 20, 80))); addChild(Vignette::create()); auto layer = Layer::create(); layer->setTag(1); addChild(layer); auto bg = LayerColor::create(C4Fto4B(0.12f, 0.02f, 0.15f, 1.0f), visibleSize.width, visibleSize.height); bg->setPositionY(PY(0.82f)); addChild(bg); auto hooker = TopAnchor::create(); addChild(hooker, 1); auto pMenu = Menu::create(); pMenu->setPosition(Point::ZERO); //hooker->addChild(bg); hooker->addChild(pMenu); auto txt1 = Label::createWithTTF(LS("HowToPlay"), NORMAL_TTF, 48.0f); txt1->setPosition(VCP(0.22f, 0.935f)); txt1->setAnchorPoint(Point(0, 0.5f)); txt1->setHorizontalAlignment(TextHAlignment::LEFT); txt1->setColor(Color3B::WHITE); hooker->addChild(txt1); //addChild(txt1, 5); auto btnBack = MAKEBUTTON("btnBackBlackUp", "btnBackBlackDn", HelpScene::btnBackPressed); pMenu->addChild(btnBack, 2); btnBack->setPosition(VCP(0.03f, 0.935f)); btnBack->setAnchorPoint(Point(0, 0.5f)); auto playerLayer = makeItem("manRt1", LS("HelpPlayer"), '@'); playerLayer->setPosition(CP(0.2f, 0.80f)); layer->addChild(playerLayer); auto robotLayer = makeItem("robot", LS("HelpRobot"), 'R'); robotLayer->setPosition(CP(0.2f, 0.50f)); robotLayer->SPRITEREF->runAction( RepeatForever::create(Sequence::createWithTwoActions( ScaleTo::create(1.0f, 1.0f), ScaleTo::create(1.0f, 0.9f) ))); layer->addChild(robotLayer); auto holeLayer = makeItem("hazard", LS("HelpBlackhole"), '!'); holeLayer->setPosition(CP(0.2f, 0.10f)); holeLayer->SPRITEREF->runAction(RepeatForever::create(RotateBy::create(2.0f, 365.0f))); holeLayer->SPRITEREF->runAction(RepeatForever::create(Sequence::createWithTwoActions( TintTo::create(0.5f, 210, 255, 255), TintTo::create(0.5f, 255, 0, 0) ))); layer->addChild(holeLayer); auto starLayer = makeItem("dronesGoal", LS("HelpStar"), 'X'); starLayer->setPosition(CP(0.2f, -0.10f)); starLayer->SPRITEREF->runAction(RepeatForever::create(Sequence::createWithTwoActions( TintTo::create(1.0f, 255, 255, 255), TintTo::create(1.0f, 255, 255, 0) ))); starLayer->SPRITEREF->runAction(RepeatForever::create(Sequence::createWithTwoActions( DelayTime::create(10.0f), RotateBy::create(1.0, -360) ))); layer->addChild(starLayer); auto gemLayer = makeItem("gem", LS("HelpGem"), 'g'); gemLayer->setPosition(CP(0.2f, -0.30f)); layer->addChild(gemLayer); auto creditsY = -0.20f; auto creditsLayer3 = makeText(LS("HelpConclusion"), 38.0f); creditsLayer3->setPosition(CP(0.5f, creditsY-0.3f)); creditsLayer3->setHorizontalAlignment(TextHAlignment::CENTER); creditsLayer3->setAnchorPoint(Point(0.5f, 1.0f)); layer->addChild(creditsLayer3); auto facebook = MAKESPRITE("facebook"); facebook->setPosition(CP(0.5f, creditsY - 0.6f)); layer->addChild(facebook); return true; }
void KeyboardManager::createKeyboardListener() { auto keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyPressed = CC_CALLBACK_2(KeyboardManager::onKeyPressed, this); keyboardListener->onKeyReleased = CC_CALLBACK_2(KeyboardManager::onKeyReleased, this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener, this); }