一、CCMenu
遊戲中的菜單必不可少,CCMenu正是你想要的。
要建立CCMenu,你必須有CCMenuItem對象,CCMenuItem便是你菜單中的某個選項,可以為圖片、文字等
cocos2d為menu item提供了必要的轉換方法,比如CCMenuItemLabel你可以通過CCLabelBMFont得到;遊戲中某些開關,比如聲音開關可以用CCMenuItemToggle對象
每一個CCMenuItem都可以在建立的時候綁定某個對象的方法,當這個CCMenuItem被點擊的時候會觸發這個方法
二、CocosDenshion
cocos2d中整合了CocosDenshion,不過遊戲中我們一般都是整個背景音樂或者來點音效,所以我們只需要用SimpleAudioEngine就可以了。
SimpleAudioEngine其實是對CDAudioManager進行了一些封裝,我們暫時不去關注細節實現,先看看怎麼使用
這是一段通用的代碼,用來確保建立SimpleAudioEngine對象成功
// Indicate that we are trying to start up the Audio Manager [CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID]; //Init audio manager asynchronously as it can take a few seconds //The FXPlusMusicIfNoOtherAudio mode will check if the user is // playing music and disable background music playback if // that is the case. [CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio]; //Wait for the audio manager to initialise while ([CDAudioManager sharedManagerState] != kAMStateInitialised) { [NSThread sleepForTimeInterval:0.1]; } //At this point the CocosDenshion should be initialized // Grab the CDAudioManager and check the state CDAudioManager *audioManager = [CDAudioManager sharedManager]; if (audioManager.soundEngine == nil || audioManager.soundEngine.functioning == NO) { CCLOG(@"CocosDenshion failed to init, no audio will play."); managerSoundState = kAudioManagerFailed; } else { [audioManager setResignBehavior:kAMRBStopPlay autoHandle:YES]; soundEngine = [SimpleAudioEngine sharedEngine]; managerSoundState = kAudioManagerReady; CCLOG(@"CocosDenshion is Ready"); }
當對象成功建立以後,便可以使用這個對象了,預先載入的過程會hang住程式,所以不要在主線程中進行聲音的預先載入
[soundEnginepreloadBackgroundMusic:trackFileName];
[soundEngineplayBackgroundMusic:trackFileNameloop:YES];
[CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID];
設定採樣率,可以在CocosDenshion.h中看到各種採樣率的宏定義,可以根據自己的音效檔來設定,注意:當你音效檔低於設定的採樣率時,會使用設定的採樣率而產生記憶體的浪費。
[CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio];
共有這幾種模式:
kAMM_FxOnly,//!Other apps will be able to play audio
kAMM_FxPlusMusic,//!Only this app will play audio
kAMM_FxPlusMusicIfNoOtherAudio,//!If another app is playing audio at start
up then allow it to continue and don't play music
kAMM_MediaPlayback,//!This app takes over audio e.g music player app
kAMM_PlayAndRecord//!App takes over audio and has input and output
都很好懂,就不一一翻譯了