最近一直在用cocos2dx做一个win32的项目,项目整体还算顺利,但毕竟第一次做cocos2dx,用的还是2.2.5版本的,所以还是碰到了很多小问题!
今天来写写音乐滑动开关------------ 项目需要,加上一直很羡慕iphone、Android等爪机上的滑动的开关,为了让项目稍微再炫酷一点,就开动了。
-------------------------------------------首先,音乐开关的判断逻辑让我纠结很一阵,先看我的第一部分“问题”代码:-----------------------------------------------
音乐开关回调函数:
<span style="font-size:10px;color:#FF6600;">
<span style="font-size:12px;color:#33CC00;">void OptionLayer::music_trigger_callback(CCObject* pSender){
if (SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying())
{
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
else
{
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
}</span></span>
函数中判断,若当前背景音乐为播放状态,则暂停音乐;若当前背景音乐为暂停状态,则继续播放。逻辑没有问题,但调试时,总是暂停音乐后,便无法继续播放。
----------------------------纠结很久,没有结果------------------------
后来便继续研究怎么做滑动开关-----------------
滑动开关做起来不那么困难----------使用CCControl-------------
先贴上代码-----------------------------------------------------
// SwitchScene.h
#ifndef __SwitchScene__
#define __SwitchScene__
#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC_EXT;
class SwitchScene :public CCControlSwitch //注意
{
public:
bool init();
CREATE_FUNC(SwitchScene);
static cocos2d::CCScene *scene();
void valueChanged(CCObject* sender, CCControlEvent controlEvent);
cocos2d::CCLabelTTF *ttf;
};
#endif
---------------------------------------------------------------------
// SwitchScene.cpp
#include "SwitchScene.h"
#include "cocos-ext.h"
USING_NS_CC_EXT;
USING_NS_CC;
using namespace CocosDenshion;
bool SwitchScene::init()
{
if (!CCControlSwitch::init())
{
return false;
}
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCControlSwitch *switch1 = CCControlSwitch::create(
CCSprite::create("2.png"), //遮盖层图片
CCSprite::create("on.png"), //开状态图片
CCSprite::create("off.png"), //关状态图片
CCSprite::create("1.png") //开关按钮图片
//CCLabelTTF::create("On", "Arial-BoldMT", 20), //开文字标签
//CCLabelTTF::create("Off", "Arial-BoldMT", 20) //关文字标签
);
this->setPosition(ccp(800,450));
switch1->setTouchPriority(kCCMenuHandlerPriority * 2 - 1); // 弹窗相关
this->setTouchEnabled(true); //
this->addChild(switch1,55);
//添加动作事件
switch1->addTargetWithActionForControlEvents(this, cccontrol_selector(SwitchScene::valueChanged), CCControlEventValueChanged);
return true;
}
CCScene *SwitchScene::scene()
{
CCScene *scene = CCScene::create();
SwitchScene *layer = SwitchScene::create();
scene->addChild(layer);
return scene;
}
//音乐开关回调函数
void SwitchScene::valueChanged(CCObject* sender, CCControlEvent controlEvent)
{
CCControlSwitch* pSwitch = (CCControlSwitch*)sender;
if (pSwitch->isOn())
{
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
else
{
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
}
看完上面的代码,再回到之前的代码,就很清楚了。关键在于上面的音乐开关回调函数的判断逻辑,这也是让我纠结了一会儿的地方,后来者多多注意!!!
贴上素材:
最后贴上效果图。
相关参考:
http://blog.csdn.net/somestill/article/details/10270703
http://www.myexception.cn/operating-system/1457863.html