cocos2dx3.0 制作音效开关

MenuItemToggle类可以实现多种状态的切换,我们可以用这个类来实现音效开关。首先我准备了4张图片,来制作两个MenuItemImage按钮


制作menuItemImage按钮如下,

auto musicOnItem = MenuItemImage::create("music1.png","music2.png");
	musicOnItem->setUserData((void *)"ON");
	auto musicOffItem = MenuItemImage::create("music3.png","music4.png");
	musicOffItem->setUserData((void *)"OFF");
可以看到我创建按钮的同时,还给这两个按钮设置了userData这个属性,等下我们会用到它。下面来制作MenuToggle按钮

auto menuToggle = MenuItemToggle::createWithCallback([](Ref* obj){
		MenuItemFont *item =(MenuItemFont*)((MenuItemToggle *)obj)->getSelectedItem();
		char* musicState = (char*)item->getUserData();
		if (musicState == "ON")
		{
			SimpleAudioEngine::getInstance()->playBackgroundMusic("AcientRemain.mp3",true);
		}
		else{
			SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
		}
	},musicOnItem,musicOffItem,NULL);

	menuToggle->setPosition(winsize.width*0.1f,winsize.height*0.9f);
	auto menu = Menu::create(menuToggle,NULL);
	menu->setPosition(Point::ZERO);
	this->addChild(menu,5);
可以看到,制作切换按钮时,我用lambda表达式设置为它的callback函数,函数体里面,取到上面两个按钮的userdata属性,根据userData属性的不同来设置音乐状态是否开启。




你可能感兴趣的:(cocos2dx,3.0整理收集)