Exemplo n.º 1
0
// on "init" you need to initialize your instance
bool VictoryScene::init()
{
	if (!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	// Victory label
	auto victory = Label::createWithTTF("Victory!", "fonts/arial.ttf", 32);
	victory->setPosition(Point(visibleSize.width / 2, visibleSize.height / 4 * 3));
	victory->setColor(cocos2d::Color3B(0, 255, 0));
	victory->setScale(2);
	this->addChild(victory);

	// Menu
	auto retry = MenuItemFont::create("Retry", CC_CALLBACK_1(VictoryScene::Retry, this));
	retry->setPosition(Point(visibleSize.width / 2, visibleSize.height / 4 * 2));

	auto goBack = MenuItemFont::create("Go Back", CC_CALLBACK_1(VictoryScene::GoBack, this));
	goBack->setPosition(Point(visibleSize.width / 2, visibleSize.height / 4 * 1));

	auto *menu = Menu::create(retry, goBack, NULL);
	menu->setPosition(Point(0, 0));
	this->addChild(menu);

	// Music
	auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
	audio->preloadBackgroundMusic(WIN_MUSIC);
	audio->playBackgroundMusic(WIN_MUSIC, true);
	return true;
}
Exemplo n.º 2
0
// on "init" you need to initialize your instance
bool Registrarse::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();

    /// Crea el fondo de la pantalla del menu "Registrarse" del juego
    auto sprite = Sprite::create("Fondos/registrarse.jpg");

    /// Posiciona el sprite (fondo de pantalla) para que quede centralizado en la pantalla
    sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    /// Hace visible el fondo de pantalla
    this->addChild(sprite, 0);
	
	createMenu();
    
	/// Se utiliza para reproducir la musica cuando se cambia a esta pantalla (registrarse).
	auto sound = CocosDenshion::SimpleAudioEngine::getInstance();
	sound->stopBackgroundMusic();
	sound->playBackgroundMusic("Music/cancion4.mp3", true);

    return true;
}
Exemplo n.º 3
0
bool AudioScene::init()
{
	if (!Layer::init())
	{
		return false;
	}

	auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
	audio->preloadBackgroundMusic("hungerland.wav");
	audio->playBackgroundMusic("hungerland.wav");

	auto eventListener = cocos2d::EventListenerKeyboard::create();
	eventListener->onKeyPressed = [audio](cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
	{
		switch (keyCode)
		{
		case cocos2d::EventKeyboard::KeyCode::KEY_SPACE:
		{
			if (audio->isBackgroundMusicPlaying())
			{
				audio->pauseBackgroundMusic();
			}
			else
			{
				audio->resumeBackgroundMusic();
			}
			break;
		}
		case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
		{
			audio->playBackgroundMusic("noncombat.wav");
			break;
		}
		case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
		{
			audio->playBackgroundMusic("hungerland.wav");
			break;
		}
		}
	};

	_eventDispatcher->addEventListenerWithFixedPriority(eventListener, 2);

	return true;
}
Exemplo n.º 4
0
bool CredditScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    Size visibleSizec;
    Vec2 originc;
    
    visibleSizec = Director::getInstance()->getVisibleSize();
    originc = Director::getInstance()->getVisibleOrigin(); //Vec2
    
    bgc = Sprite::create("credit_background");
    bgc-> setScale(0.4);
    bgc->setPosition(originc.x + visibleSizec.width/2, originc.y + visibleSizec.height/2);
    this->addChild(bgc);
    
    creds1 = Sprite::create("credits1.png");
    creds1-> setScale(0.5);
    creds1-> setPosition(originc.x + visibleSizec.width/2, originc.y + visibleSizec.height/2 - creds1->getContentSize().height/4);
    this-> addChild(creds1);
    creds2 = Sprite::create("credits2.png");
    creds2-> setScale(0.5);
    creds2-> setPosition(originc.x + visibleSizec.width/2, originc.y + visibleSizec.height/2 - creds2->getContentSize().height/2);
    this-> addChild(creds2);
    creds3 = Sprite::create("credits3.png");
    creds3-> setScale(0.5);
    creds3-> setPosition(originc.x + visibleSizec.width/2, originc.y + visibleSizec.height/2 - creds3->getContentSize().height/2);
    this-> addChild(creds3);
    creds4 = Sprite::create("credits4.png");
    creds4-> setScale(0.5);
    creds4-> setPosition(originc.x + visibleSizec.width/2, originc.y + visibleSizec.height/2 - creds4->getContentSize().height/2);
    this-> addChild(creds4);

    this->schedule(schedule_selector(CredditScene::startC1), 8.0f,1, 0.05f);
    this->schedule(schedule_selector(CredditScene::startC2), 8.0f,1, 12.5f);
    this->schedule(schedule_selector(CredditScene::startC3), 8.0f,1, 36.0f);
    this->schedule(schedule_selector(CredditScene::startC4), 8.0f,1, 64.5f);
    
    auto touchListener = EventListenerTouchOneByOne::create();
    touchListener -> setSwallowTouches(true);
    // setup the callback
    touchListener -> onTouchMoved =
    CC_CALLBACK_2(CredditScene::onTouchMoved, this);
    touchListener -> onTouchBegan =
    CC_CALLBACK_2(CredditScene::onTouchBegan, this);
    touchListener -> onTouchEnded =
    CC_CALLBACK_2(CredditScene::onTouchEnded, this);
    
    _eventDispatcher-> addEventListenerWithSceneGraphPriority(touchListener, bgc);
    
    backgroundMusic2->playBackgroundMusic("background.mp3", true);
    
    return true;
}
void GUISoundManager::playNextBackgroundMusic() {
	if (enabled && backgroundSounds.size()>0) {
		stopBackgroundMusic();

		if (backgroundTitle < (signed)backgroundSounds.size()-1)
			backgroundTitle++;
		else backgroundTitle = 0;

		playBackgroundMusic();
	}
}
Exemplo n.º 6
0
// on "init" you need to initialize your instance
bool LevelSelectScene::init() {
	// 1. super init first
	if (!Layer::init()) { // if there is a mistake then we terminate the program, it couldnt launch
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Point origin = Director::getInstance()->getVisibleOrigin();

	// add a label shows "Menu Inicio"
	// create and initialize a label

	auto label1 = LabelTTF::create("Seleccionar nivel", "Book Antigua", 50);
	auto label2 = LabelTTF::create("Nivel 1", "Book Antigua", 20);
	auto label3 = LabelTTF::create("Nivel 2", "Book Antigua", 20);
	auto label4 = LabelTTF::create("Nivel3", "Book Antigua", 20);

	// position the label on the center of the screen
	label1->setPosition(Point(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * .64f));
	label2->setPosition(Point(visibleSize.width / 4, origin.y + visibleSize.height * 0.18f));
	label3->setPosition(Point(2 * visibleSize.width / 4, origin.y + visibleSize.height * 0.18f));
	label4->setPosition(Point(3 * visibleSize.width / 4, origin.y + visibleSize.height * 0.18f));

	// add the label as a child to this layer
	this->addChild(label1, 1);
	this->addChild(label2, 1);
	this->addChild(label3, 1);
	this->addChild(label4, 1);

	// Crear el fondo del menu del juego
	auto sprite = Sprite::create("GameMenu/0000.jpg");

	// 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);

	createMenu();

	// Reproducir la musica de la seleccion del nivel: quiza sea mejor dejar la misma del menu
	// principal y cambiarla cuando se haya iniciado el nivel. Se deja aqui por propositos
	// ilustrativos
	auto sound = CocosDenshion::SimpleAudioEngine::getInstance();
	sound->stopBackgroundMusic();
	sound->playBackgroundMusic("Music/LevelSelect.mp3", true);

	return true;
}
void GUISoundManager::playBackgroundMusicWithFadeIn() {
	if (play == false && fadeIN == false) {
		fadeIN = true;
		fadeGain = 0;

		if (backgroundSounds.size()>0) {
			for (unsigned int i = 0; i < backgroundSounds.size(); i++) {
				GameEvent eve(GameEvent::E_SET_SOUND_GAIN, &GameEventData(0), 0x0);
				GameEngine::sendEvent(backgroundSounds[i], &eve);
			}
		}

		playBackgroundMusic();
	}
}
Exemplo n.º 8
0
void LoadingScene::LoadingMusic()
{
    audioloaded = true;
    auto Audio = CocosDenshion::SimpleAudioEngine::getInstance();
    Audio->preloadEffect("explodeEffect.mp3");
    Audio->preloadEffect("hit.mp3");
    Audio->preloadEffect("boom2.mp3");
    Audio->preloadEffect("boom.mp3");
    Audio->preloadBackgroundMusic("Orbital Colossus_0.mp3");
    //Audio->preloadBackgroundMusic("Star_Chaser.mp3");
    
    // Music By Matthew Pable (http://www.matthewpablo.com/)
    // Licensed under CC-BY 3.0 (http://creativecommons.org/licenses/by/3.0/)
    Audio->playBackgroundMusic("Flux2.mp3");
}
Exemplo n.º 9
0
// We  initialize our instance
bool OptionsScene::init() {
	// 1. super init first
	if (!Layer::init()) { // if there is a mistake then we terminate the program, it couldnt launch
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Point origin = Director::getInstance()->getVisibleOrigin();

	// add a label shows "Creditos" create and initialize labels

	auto labelTitulo = LabelTTF::create("Opciones", "Tahoma", 32);

	// position the label on the upper center of the screen
	labelTitulo->setPosition(Point(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * .88f));

	// add the label as a child to this layer
	this->addChild(labelTitulo, 1);

	// We add the devs labels
	this->showNames(origin, visibleSize);

	// Creates the background of the game menu.
	auto sprite = Sprite::create("GameMenu/0000.jpg"); // sprites are important, those are the images
	// 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);

	createMenu(); // We bring to live this scene.

	// Reproducir la musica de la seleccion del nivel: quiza sea mejor dejar la misma del menu
	// principal y cambiarla cuando se haya iniciado el nivel. Se deja aqui por propositos
	// ilustrativos
	auto sound = CocosDenshion::SimpleAudioEngine::getInstance();
	sound->stopBackgroundMusic(); // this steps are to change tracks.
	sound->playBackgroundMusic("Music/Options.mp3", true); // We use a piece of music we already have and reproduce it for the options scene.

	return true; // we managed to bring frankestein alive, I mean, the game.
}
bool
HelloWorld::init()
{
    if (!Layer::init())
    {
        return false;
    }

    auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
    audio->preloadBackgroundMusic("sfx/An_Adventure_Awaits.mp3");
    audio->preloadBackgroundMusic("sfx/BEAD.mp3");
    audio->preloadEffect("sfx/sound4.wav");
    audio->preloadEffect("sfx/sound5.wav");
    audio->playBackgroundMusic("sfx/BEAD.mp3");

    Size visibleSize = Director::getInstance()->getVisibleSize();

    auto startGameButton = Label::createWithTTF("Start the game", "fonts/Marker Felt.ttf", 24);
    startGameButton->setPosition(
        Vec2(
            visibleSize.width/2,
            visibleSize.height/2 - startGameButton->getContentSize().height
        )
    );
    auto touchListener = EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = [](Touch* touch, Event* event) -> bool {
        auto scene = Game::createScene();
        Director::getInstance()->pushScene(scene);
        return true;
    };
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(
        touchListener,
        startGameButton
    );
    this->addChild(startGameButton, 1);

    return true;
}
void SGSound::playBackgroundMusic( const char* Filepath,bool loop )
{
    //onSound2;
    if(onSound2 ==true)
        playBackgroundMusic(Filepath,loop);
}
Exemplo n.º 12
0
bool GameScene::init()
{
    if (!Layer::init())return false;
    
    
    initPlist();
    initEffect();
    
    //set game status
    Config::getInstance()->setGameSatus(ING);
    Config::getInstance()->setScore(0);//rest score
    
    //loding effect
    auto _SimpleAudioEngine = SimpleAudioEngine::getInstance();
    _SimpleAudioEngine->preloadEffect(air_shoot_effect1);
    _SimpleAudioEngine->preloadEffect(ship_explode_effect0);
    
    //init game map
    //init enemy type
    switch (levelNum)
    {
        case GAMEMAP1://0
            if (Config::getInstance()->getmusicState())
            {
                auto simpleAudio = SimpleAudioEngine::getInstance();
                simpleAudio->preloadBackgroundMusic(battle_bg_stage0);
                simpleAudio->setBackgroundMusicVolume(1.0f);
                simpleAudio->playBackgroundMusic(battle_bg_stage0, true);
            }
            addMap("Map1.png");
            levelScore = BOOS_LEVEL1;
            break;
        case GAMEMAP2://1
            if (Config::getInstance()->getmusicState())
            {
                auto simpleAudio = SimpleAudioEngine::getInstance();
                simpleAudio->preloadBackgroundMusic(battle_bg_stage1);
                simpleAudio->setBackgroundMusicVolume(1.0f);
                simpleAudio->playBackgroundMusic(battle_bg_stage1, true);
            }
            addMap("Map2.png");
            levelScore = BOOS_LEVEL2;
            //add particle
            Kit::addParticle(snow_plist, this, VisibleRect::top());
            break;
        case GAMEMAP3://2
            if (Config::getInstance()->getmusicState())
            {
                auto simpleAudio = SimpleAudioEngine::getInstance();
                simpleAudio->preloadBackgroundMusic(battle_bg_stage2);
                simpleAudio->setBackgroundMusicVolume(1.0f);
                simpleAudio->playBackgroundMusic(battle_bg_stage2, true);
            }
            addMap("Map3.png");
            levelScore = BOOS_LEVEL3;
            break;
            
        case GAMEMAP4://3
            if (Config::getInstance()->getmusicState())
            {
                auto simpleAudio = SimpleAudioEngine::getInstance();
                simpleAudio->preloadBackgroundMusic(battle_bg_stage2);
                simpleAudio->setBackgroundMusicVolume(1.0f);
                simpleAudio->playBackgroundMusic(battle_bg_stage2, true);
            }
            addMap("Map4.png");
            levelScore = BOOS_LEVEL4;
            //add fire paticle
            Kit::addParticle(battle_fire_bg_particle_plist, this, VisibleRect::top());
            break;
        default:
            log("there's no game map to do !");
            return false;
            break;
    }
    
    //add logo one top-left
    auto	logoShip = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(SHIP_FILE_NAME));
    float offset = logoShip->getContentSize().width / 2;
    logoShip->setScale(0.8f);
    auto winsize = Director::getInstance()->getWinSize();
    logoShip->setPosition(Vec2(offset, winsize.height - offset));
    this->addChild(logoShip, SHIP_Z_ORDER);
    
    
    
    //set life value  beside of logoShip
    Config::getInstance()->setShipLife(SHIP_LIFES);
    __String life("X");
    life.appendWithFormat("%02d", Config::getInstance()->getShipLife());
    lifeValue = Label::createWithSystemFont(life.getCString(), "Arial", 12);
    lifeValue->setPosition(Vec2(offset * 3, winsize.height - offset));
    lifeValue->setColor(Color3B::RED);
    this->addChild(lifeValue, SHIP_Z_ORDER);
    
    
    //add score
    __String tempscore("得分:");
    tempscore.appendWithFormat("%07d", Config::getInstance()->getScore());
    score = Label::createWithSystemFont(tempscore.getCString(), "Arial", 12);
    score->setPosition(Vec2(winsize.width - 45, winsize.height - offset));
    score->setColor(Color3B::RED);
    this->addChild(score, SHIP_Z_ORDER);
    
    
    
    
    ship = Ship::creatShip(this, 0, SHIP_LIFE_VALUE);
    auto initPosition = VisibleRect::center();
    ship->setPosition(Vec2(initPosition.x, initPosition.y - 120.0f));
    this->addChild(ship, SHIP_Z_ORDER);
    
    
    //add bone btn
    auto bone_btn_sprite = Sprite::create(btn_bone_res);
    bone_btn_sprite->setScale(0.8f);
    auto bone_btn = MenuItemSprite::create(bone_btn_sprite, nullptr, [&](Ref* _bone_btn){
        
        //处理炸弹效果
        log("bone released ......");
        
        //can shake
        auto j = JumpBy::create(0.5f, Vec2::ZERO, 5, 5);
        this->runAction(j);
        
        auto config = Config::getInstance();
        //remove enemy and bullet
        for (auto bullet : *config->enemy_bullet_list)
        {
            bullet->boneDestory();
        }
        
        for (auto enemy : *config->enemy_list)
        {
            //effect it
            log("effect it ......");
            enemy->boneDestory(this);
        }
        config->enemy_bullet_list->clear();
        config->enemy_list->clear();
        
    });
    auto menue = Menu::create(bone_btn, NULL);
    menue->setPosition(Vec2(35, 200));
    this->addChild(menue, BTN_BACK_Z_ORDER);
    menue->runAction(Kit::creatEaseSineInOut(100.0f));
    
    
    
    
    //add back btn
    auto btn_sprite = Sprite::createWithTexture(Director::getInstance()->getTextureCache()->addImage(btn_back_res));
    btn_sprite->setColor(Color3B(0, 245, 255));
    auto btn_back = MenuItemSprite::create(btn_sprite, nullptr, [&](Ref* item){
        auto menuSprite = (MenuItemSprite*)item;
        auto scale = ScaleBy::create(0.2f, 1.1);
        auto jumpToGameLevel = CallFunc::create([](){
            
            auto config=Config::getInstance();
            
            if (config->getmusicState()) SimpleAudioEngine::getInstance()->stopBackgroundMusic();// 停止当前背景音乐
            
            if (config->getmusicState())
            {
                SimpleAudioEngine::getInstance()->playBackgroundMusic(main_bg_stage1, true);
            }
          
            
            Director::getInstance()->replaceScene(TransitionFade::create(1.2f, GameLevelLayer::creatScene()));
        });
        
        //call back
        std::function<void()> releaseResources = [&](){
            this->releaseR();
        };
        menuSprite->runAction(Sequence::create(CallFunc::create(releaseResources), scale, scale->reverse(), jumpToGameLevel, NULL));
    });
    
    
    
    
    menue = Menu::create(btn_back, NULL);
    auto btn_back_position = VisibleRect::rightBottom();
    offset = btn_sprite->getContentSize().width / 2;
    menue->setPosition(Vec2(btn_back_position.x - 50, btn_back_position.y + 25));
    this->addChild(menue, BTN_BACK_Z_ORDER);
    menue->runAction(Kit::creatEaseSineInOut(100.0f));
    
    
    
    
    
    
    //添加敌机
    this->schedule(schedule_selector(GameScene::addEnemy), 2.0f, kRepeatForever, 1.2f);
    
    this->scheduleUpdate();
    
    //初始化地图移动
    this->scheduleOnce(schedule_selector(GameScene::initMoveMap), 1.2f);
    
    
    
    
    return true;
}
Exemplo n.º 13
0
bool StartScene::init(){
	if(!Layer::init()){
		return false;
	} 
	auto simple = SimpleAudioEngine::getInstance();

	auto uilayer = GUIReader::getInstance()->widgetFromJsonFile("startUI/Start.json");
	this->addChild(uilayer);
	auto btnStart = dynamic_cast<Button *>(uilayer->getChildByName("btn_start"));
	btnStart->addTouchEventListener([](Ref* ref,Widget::TouchEventType t){
		if (t == Widget::TouchEventType::ENDED)
		{
			Director::getInstance()->replaceScene(SelectLayer::createScene());
			SimpleAudioEngine::getInstance()->playEffect("Music/btnOver.mp3");
		}
		
	}); // button start game
	auto btnExit = dynamic_cast<Button *>(uilayer->getChildByName("btn_exit"));
	btnExit->addTouchEventListener([](Ref* ref,Widget::TouchEventType t){
		if (t == Widget::TouchEventType::ENDED)
		{   
			SimpleAudioEngine::getInstance()->playEffect("Music/btnOver.mp3");
			Director::getInstance()->end();
		}

	});//exit game
	auto btnHelp = dynamic_cast<Button *>(uilayer->getChildByName("help"));
	btnHelp->addTouchEventListener([=](Ref* ref,Widget::TouchEventType t){
		if (t == Widget::TouchEventType::BEGAN)
		{   
			Director::getInstance()->replaceScene(LevelLayer::createScene());
		}

	});
	auto instance = SimpleAudioEngine::getInstance();
	auto check = dynamic_cast<CheckBox*> (uilayer->getChildByName("music_check"));
	auto isMusicON = UserDefault::getInstance()->getBoolForKey("isMusicON",true);
	 instance->playBackgroundMusic("Music/battle1.mp3",true);
	if (isMusicON)
	{     
		  check->setSelectedState(false); 
	}
	else
	{   
		check->setSelectedState(true);
		instance->pauseBackgroundMusic();
		instance->setEffectsVolume(0.0f);
	}
	check->addEventListener([=](Ref* r,CheckBox::EventType t){
		if (t == CheckBox::EventType::SELECTED)
		{   
			UserDefault::getInstance()->setBoolForKey("isMusicON",false);
		   // SimpleAudioEngine::getInstance()->stopAllEffects();
			SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
			instance->setEffectsVolume(0.0f);
		}else
		{  
			UserDefault::getInstance()->setBoolForKey("isMusicON",true);
		    SimpleAudioEngine::getInstance()->setEffectsVolume(1.0f);
			SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
		}
	});
	auto money = GameManager::getInstance()->getStageMoney();
	log("%d................",money);
	return true;
}
Exemplo n.º 14
0
// 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));

    // add the sprite as a child to this layer
    this->addChild(sprite, 0);
    

    auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
    audio->playBackgroundMusic("tot.ogg", false);
    this->playing = true;


    auto listener1 = EventListenerTouchOneByOne::create();
    //TODO: get lambada passing the this variable
    //listener1->onTouchBegan = [this](Touch* touch, Event* event){
    listener1->onTouchBegan = [this](auto touch, auto event){
      this->play_toggle();
      return true; // if you are consuming it
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);

    return true;
}
Exemplo n.º 15
0
void Mainpage::playBGM() {
    auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
    if (!audio->isBackgroundMusicPlaying()) {
        audio->playBackgroundMusic(("musics/main_bgm.mp3"));
    }
}
Scene* Chapter13::createScene()
{
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // some upfront items that we need
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto dirs = Director::getInstance();
    Size visibleSize = dirs->getVisibleSize();
    Vec2 origin = dirs->getVisibleOrigin();
    
    Size playingSize = Size(visibleSize.width, visibleSize.height - (visibleSize.height/8)); // actual playing size to work with

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto scene = Scene::create();
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a node to hold non-sprites.
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto nodeItems = Node::create();
    nodeItems->setName("nodeItems");
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a node to hold menu
    // create a menu
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto menuNode = Node::create();
    menuNode->setName("menuNode");
    int index = 2;
    
    auto menuItem1 = MenuItemFont::create("Play Music");
    menuItem1->setFontNameObj("fonts/Marker Felt.ttf");
    menuItem1->setFontSizeObj(32);
    menuItem1->setName("menuItem1");
    menuItem1->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                           (Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - (index) * 40));
    menuItem1->setCallback([&](cocos2d::Ref *sender) {
        auto dirs = Director::getInstance()->getRunningScene();
        auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
        
        audio->playBackgroundMusic("music.mp3");
        
        auto anode = dirs->getChildByName("menuNode");
        auto bnode = anode->getChildByName("menu");
        auto cnode = bnode->getChildByName("menuItem1");
        cnode->setVisible(false);
        cnode = bnode->getChildByName("menuItem2");
        cnode->setVisible(true);
    });
    
    auto menuItem2 = MenuItemFont::create("Stop Music");
    menuItem2->setFontNameObj("fonts/Marker Felt.ttf");
    menuItem2->setFontSizeObj(32);
    menuItem2->setName("menuItem2");
    menuItem2->setVisible(false);
    menuItem2->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                           (Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - (index) * 40));
    menuItem2->setCallback([&](cocos2d::Ref *sender) {
        auto dirs = Director::getInstance()->getRunningScene();
        auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
        
        audio->stopBackgroundMusic("music.mp3");
        
        auto anode = dirs->getChildByName("menuNode");
        auto bnode = anode->getChildByName("menu");
        auto cnode = bnode->getChildByName("menuItem2");
        cnode->setVisible(false);
        cnode = bnode->getChildByName("menuItem1");
        cnode->setVisible(true);
    });
    
    auto menuItem3 = MenuItemFont::create("Play Effect");
    menuItem3->setFontNameObj("fonts/Marker Felt.ttf");
    menuItem3->setFontSizeObj(32);
    menuItem3->setName("menuItem3");
    menuItem3->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                           (Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - (++index) * 40));
    menuItem3->setCallback([&](cocos2d::Ref *sender) {
        auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
        
        audio->playEffect("alert.mp3");
    });
    
    auto menu = Menu::create(menuItem1, menuItem2, menuItem3, NULL);
    menu->setName("menu");
    menuNode->addChild(menu, 1);
    menu->setPosition(Vec2::ZERO);
    
    scene->addChild(menuNode, 2);
    
    // return the scene
    return scene;
}
Exemplo n.º 17
0
bool ComAudio::serialize(void* r)
{
    bool ret = false;
    do
    {
        CC_BREAK_IF(r == nullptr);
        SerData *serData = (SerData *)(r);
        const rapidjson::Value *v = serData->_rData;
        stExpCocoNode *cocoNode = serData->_cocoNode;
        CocoLoader *cocoLoader = serData->_cocoLoader;
        const char *className = nullptr;
        const char *comName = nullptr;
        const char *file = nullptr;
        std::string filePath;
        int resType = 0;
        bool loop = false;
        if (v != nullptr)
        {
            className = DICTOOL->getStringValue_json(*v, "classname");
            CC_BREAK_IF(className == nullptr);
            comName = DICTOOL->getStringValue_json(*v, "name");
            const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
            CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
            file = DICTOOL->getStringValue_json(fileData, "path");
            CC_BREAK_IF(file == nullptr);
            resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
            CC_BREAK_IF(resType != 0);
            loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false;
        }
        else if (cocoNode != nullptr)
        {
            className = cocoNode[1].GetValue(cocoLoader);
            CC_BREAK_IF(className == nullptr);
            comName = cocoNode[2].GetValue(cocoLoader);
            stExpCocoNode *pfileData = cocoNode[4].GetChildArray(cocoLoader);
            CC_BREAK_IF(!pfileData);
            file = pfileData[0].GetValue(cocoLoader);
            CC_BREAK_IF(file == nullptr);
            resType = atoi(pfileData[2].GetValue(cocoLoader));
            CC_BREAK_IF(resType != 0);
            loop = atoi(cocoNode[5].GetValue(cocoLoader)) != 0? true:false;
            ret = true;
        }
        if (comName != nullptr)
        {
            setName(comName);
        }
        else
        {
            setName(className);
        }
        if (file != nullptr)
        {
            if (strcmp(file, "") == 0)
            {
                continue;
            }
            filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
        }
        if (strcmp(className, "CCBackgroundAudio") == 0)
        {
            preloadBackgroundMusic(filePath.c_str());
            setLoop(loop);
            playBackgroundMusic(filePath.c_str(), loop);
        }
        else if(strcmp(className, COMPONENT_NAME.c_str()) == 0)
        {
            preloadEffect(filePath.c_str());
        }
        else
        {
            CC_BREAK_IF(true);
        }
        ret = true;
    }while (0);
    return ret;
}
Exemplo n.º 18
0
bool ComAudio::serialize(void* r)
{
    bool ret = false;
	do
	{
		CC_BREAK_IF(r == nullptr);
		SerData *serData = (SerData *)(r);
		const rapidjson::Value *v = serData->_rData;
		stExpCocoNode *cocoNode = serData->_cocoNode;
		const char *className = nullptr;
		const char *comName = nullptr;
		const char *file = nullptr;
		std::string filePath;
		int resType = 0;
		bool loop = false;
		if (v != nullptr)
		{
			className = DICTOOL->getStringValue_json(*v, "classname");
			CC_BREAK_IF(className == nullptr);
			comName = DICTOOL->getStringValue_json(*v, "name");
			const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
			CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
			file = DICTOOL->getStringValue_json(fileData, "path");
			CC_BREAK_IF(file == nullptr);
			resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
			CC_BREAK_IF(resType != 0);
			loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false;
		}
		else if (cocoNode != nullptr)
		{
			className = cocoNode[1].GetValue();
			CC_BREAK_IF(className == nullptr);
			comName = cocoNode[2].GetValue();
			stExpCocoNode *pfileData = cocoNode[4].GetChildArray();
			CC_BREAK_IF(!pfileData);
			file = pfileData[0].GetValue();
			CC_BREAK_IF(file == nullptr);
			resType = atoi(pfileData[2].GetValue());
			CC_BREAK_IF(resType != 0);
			loop = atoi(cocoNode[5].GetValue()) != 0? true:false;
			ret = true;
		}
		if (comName != nullptr)
		{
			setName(comName);
		}
		else
		{
			setName(className);
		}
		if (file != nullptr)
		{
            if (strcmp(file, "") == 0)
            {
                continue;
            }
			filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
		}
		if (strcmp(className, "CCBackgroundAudio") == 0)
		{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
			// no MP3 support for CC_PLATFORM_WP8
			std::string::size_type pos = filePath.find(".mp3");
			if (pos  == filePath.npos)
			{
				continue;
			}
			filePath.replace(pos, filePath.length(), ".wav");
#endif
			preloadBackgroundMusic(filePath.c_str());
			setLoop(loop);
			playBackgroundMusic(filePath.c_str(), loop);
		}
		else if(strcmp(className, "CCComAudio") == 0)
		{
			preloadEffect(filePath.c_str());
		}
		else
		{
			CC_BREAK_IF(true);
		}
		ret = true;
	}while (0);
	return ret;
}
Exemplo n.º 19
0
// on "init" you need to initialize your instance
bool MainMenu::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
	//multitouch listener
	auto multiTouchListener = EventListenerTouchAllAtOnce::create();
	multiTouchListener->onTouchesBegan = CC_CALLBACK_2(MainMenu::touchesBegan, this);
	multiTouchListener->onTouchesMoved = CC_CALLBACK_2(MainMenu::touchesMoved, this);
	multiTouchListener->onTouchesEnded = CC_CALLBACK_2(MainMenu::touchesEnded, this);

    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
	
	//exit
    auto closeItem = MenuItemImage::create(
                                           "ExitNormal.png",
                                           "ExitSelected.png",
										   CC_CALLBACK_1(MainMenu::menuCloseCallback, this));
	closeItem->setPosition(Vec2(origin.x + visibleSize.width / 2,
                                origin.y + visibleSize.height / 2 - closeItem->getContentSize().height));

	//start
	auto startItem = MenuItemImage::create(
		"StartNormal.png",
		"StartSelected.png",
		CC_CALLBACK_1(MainMenu::GoToGameScene, this));

	startItem->setPosition(Vec2(origin.x + visibleSize.width / 2,
		origin.y + visibleSize.height / 2 + closeItem->getContentSize().height));

	// create menu, it's an autorelease object
	auto menu = Menu::create(startItem, NULL);
	menu->setPosition(Vec2::ZERO);
	this->addChild(menu, 1);

    // create menu, it's an autorelease object
    auto menu2 = Menu::create(closeItem, NULL);
	menu2->setPosition(Vec2::ZERO);
	this->addChild(menu2, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    auto label = Label::createWithTTF("Main Menu", "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);

	//play main menu bgm
	auto audio = CocosDenshion::SimpleAudioEngine::getInstance();

	// set the background music and continuously play it.
	audio->playBackgroundMusic("MainMenu.mp3", false);

    return true;
}