Cocos2d-x with UserDefault data persistence instance: Save background music and sound settings,

Source: Internet
Author: User

Cocos2d-x with UserDefault data persistence instance: Save background music and sound settings,
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 cannot play background music

Use preloadBackgroundMusic to load the music and try again. In addition, use mp3 for background music. If not, it is very small that your mp3 format is not standard. You can use the Conversion Tool to re-convert and then try again to solve the problem. Pay attention to the correct position of the music.


Related Article

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.