Cocos2d-x using userdefault data persistence instance: Save background music and sound effects settings

Source: Internet
Author: User

Cocos2d cocos2d-x game developers iOS 8

Userdefault can store data, but it cannot be used in a flood. In general, it will not be used to store a large amount of data, and it is not as flexible as SQL statements. In addition to saving game settings, userdefault can also maintain the status of Game Genie and other objects for a long time.


An example is provided to illustrate how to use userdefault in game projects ., In the setting scenario, you can set whether to play background music and sound effects. Now, we will save the selected status to userdefault.




To set the background music and sound effects (helloworld scenario and setting scenario), we need to define two macros as keys. sound_key is the sound state key, and music_key is the background music playback state key.
# Define sound_key "sound_key"
# Define music_key "music_key"
However, these two macros need to be used in all CPP files. We can create a header file and declare these macros in this header file. The systemheader. H code of this header file is as follows:
# Include "simpleaudioengine. H"
# Define sound_key "sound_key"
# Define music_key "music_key"
We have declared two macros, including the header file simpleaudioengine. h. The header file simpleaudioengine. H is required by the cocosdenshion engine.
In Visual Studio 2012, the process of adding systemheader. h file is. First, open the helloworld project in solution, right-click classes, and choose "add"> "new item" from the right-click menu, as shown in figure 14-8.
In the displayed dialog box, select "Visual C ++"> "header file (. h) ", enter" systemheader. h, and then click Add to add the header file.


Add systemheader. h file
When using the Add systemheader. h file dialog box, we need to add the systemheader file to the header files helloworldscene. h and settingscene. h. The sample code is as follows:
#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include "SettingScene.h"#include "SystemHeader.h"class HelloWorld : public cocos2d::Layer{public:… …CREATE_FUNC(HelloWorld);};#endif // __HELLOWORLD_SCENE_H__


The main code of helloworld scenario helloworldscene. cpp is as follows:
# Include "helloworldscene. H "using_ns_cc; using namespace cocosdenshion; bool helloworld: Init (){...... return true;} void helloworld: menuitemsettingcallback (ref * psender) {auto SC = Setting: createscene (); Auto rescene = transitionjumpzoom: Create (1.0f, SC); ctor:: getinstance ()-> pushscene (rescene); If (userdefault: getinstance ()-> getboolforkey (sound_key) {① simpleaudioengine: getinstance () -> playeffect ("sound/blip.wav") ;}} void helloworld: menuitemhelpcallback (ref * psender) {menuitem * Item = (menuitem *) psender; log ("Touch help % P", item); If (userdefault: getinstance ()-> getboolforkey (sound_key) {② simpleaudioengine: getinstance () -> playeffect ("sound/blip.wav") ;}} void helloworld: menuitemstartcallback (ref * psender) {menuitem * Item = (menuitem *) psender; log ("Touch start % P", item); If (userdefault: getinstance ()-> getboolforkey (sound_key) {③ simpleaudioengine: getinstance () -> playeffect ("sound/blip.wav") ;}} void helloworld: onenter () {layer: onenter (); log ("helloworld onenter");} void helloworld:: onentertransitiondidfinish () {layer: onentertransitiondidfinish (); log ("helloworld onentertransitiondidfinish"); // play if (userdefault: getinstance ()-> getboolforkey (music_key )) {④ simpleaudioengine: getinstance ()-> playbackgroundmusic ("sound/jazzaudio", true) ;}} void helloworld: onexit () {layer: onexit (); log ("helloworld onexit");} void helloworld: onexittransitiondidstart () {layer: reset (); log ("helloworld onexittransitiondidstart");} void helloworld: cleanup () {layer: cleanup (); log ("helloworld cleanup"); // stop simpleaudioengine: getinstance ()-> stopbackgroundmusic ("sound/jazzaudio ");}


In the above Code lines ①, ②, and ③, userdefault: getinstance ()-> getboolforkey (sound_key) is used to obtain the sound_key value and obtain the Boolean value to determine whether to play the sound effect. The Code in line ④ userdefault: getinstance ()-> getboolforkey (music_key) is used to obtain the music_key value, and obtain the Boolean value to determine whether to play background music.
Next let's take a look at the main code of Init () in settingscene. cpp in the setting scenario:
#include "SettingScene.h"USING_NS_CC;using namespace CocosDenshion;bool Setting::init(){... ...UserDefault *defaults  = UserDefault::getInstance();if (defaults->getBoolForKey(MUSIC_KEY)) {①musicToggleMenuItem->setSelectedIndex(0);②} else {musicToggleMenuItem->setSelectedIndex(1);③}if (defaults->getBoolForKey(SOUND_KEY)) {④soundToggleMenuItem->setSelectedIndex(0);⑤} else {soundToggleMenuItem->setSelectedIndex(1);⑥}return true;}


The above Code sets the status of the switch menu ~ ③ The line of code sets the background music switch menu. The line ② of Code sets the switch menu to off. Otherwise, the line ③ Code sets the status to on. ④ ~ The Code in line 6 sets the sound switch menu. The Code in line 5 sets the switch menu to off. Otherwise, the Code in line 6 sets the status to on.
The code for clicking the sound switch menu in settingscene. cpp is as follows:
void Setting::menuSoundToggleCallback(Ref* pSender){auto soundToggleMenuItem = (MenuItemToggle*)pSender;log("soundToggleMenuItem %d", soundToggleMenuItem->getSelectedIndex());UserDefault *defaults  = UserDefault::getInstance();if (defaults->getBoolForKey(SOUND_KEY)) {①defaults->setBoolForKey(SOUND_KEY, false);②} else {defaults->setBoolForKey(SOUND_KEY, true);③SimpleAudioEngine::getInstance()->playEffect("sound/Blip.wav");④}}


When the first line of the above Code determines that the sound is enabled to true, use the defaults-> setboolforkey (sound_key, false) statement to set false, otherwise, use the ③ ults-> setboolforkey (sound_key, true) Statement in line ③ To set true. At the same time, use the line ④ code to play the sound effect.
The code for clicking the background music switch menu in settingscene. cpp is as follows:
void Setting::menuMusicToggleCallback(Ref* pSender){auto musicToggleMenuItem = (MenuItemToggle*)pSender;log("musicToggleMenuItem %d", musicToggleMenuItem->getSelectedIndex());UserDefault *defaults  = UserDefault::getInstance();if (defaults->getBoolForKey(MUSIC_KEY)) {①defaults->setBoolForKey(MUSIC_KEY, false);SimpleAudioEngine::getInstance()->stopBackgroundMusic();} else {defaults->setBoolForKey(MUSIC_KEY, true);SimpleAudioEngine::getInstance()->playBackgroundMusic("sound/Synth.mp3");}②}


Code ① ~ The second line is to set the background music switch menu. The code is similar to clicking the sound switch menu and will not be explained. Other major code in settingscene. cpp is as follows:
Void setting: onenter () {layer: onenter (); log ("setting onenter");} void setting: menuokcallback (ref * psender) ① {Director :: getinstance ()-> popscene (); If (userdefault: getinstance ()-> getboolforkey (sound_key) {② simpleaudioengine: getinstance () -> playeffect ("sound/blip.wav") ;}} void setting: onentertransitiondidfinish () ③ {layer: onentertransitiondidfinish (); log ("setting onentertransitiondidfinish "); if (userdefault: getinstance ()-> getboolforkey (music_key) {④ // play simpleaudioengine: getinstance ()-> playbackgroundmusic ("sound/synthmusic ", true) ;}} void setting: onexit () {layer: onexit (); log ("setting onexit") ;}void setting: onexittransitiondidstart () {layer :: onexittransitiondidstart (); log ("setting onexittransitiondidstart");} void setting: cleanup () {layer: cleanup (); log ("setting cleanup "); // stop simpleaudioengine: getinstance ()-> stopbackgroundmusic ("sound/synthmusic ");}


In line ① Of the above Code, menuokcallback is the callback function by clicking the OK menu. In line ②, the code is used to obtain the sound_key value and obtain the Boolean value to determine whether to play the sound effect. The onentertransitiondidfinish function of the Code in line ③ is called at the entry layer and the end of the transition animation. The Code in line ④ obtains the music_key value, and obtains the Boolean value to determine whether to play background music.

We can run it to save the status, and then re-run the game to see if it can be maintained. We can also go to the <Cocos2d-x project directory> \ proj. Win32 \ Debug. Win32 Directory to see if the userdefault. xml file is successfully generated.


More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to the Cocos2d-x Technology Discussion Group: 257760386 welcome to the knowledge of the IOS classroom public platform


Cocos2d-x using userdefault data persistence instance: Save background music and sound effects settings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.