【Cocos2d-X开发学习笔记】第23期:事件处理机制之按键事件

来源:互联网 发布:易云网络验证 编辑:程序博客网 时间:2024/05/22 04:28

本系列学习教程使用的是cocos2d-x-2.1.4(最新版为3.0alpha0-pre) ,PC开发环境Windows7,C++开发环境VS2010

 

 

 

一、按键事件

 

      使用IOS系统设备中只有Home键,按下Home键,程序进入后台。而使用Android系统的部分设备会有Menu键和

返回键,因此有时需要检测设备的键盘输入,使用键盘事件代理CCKeypadDelegate处理相应的事件。

CCKeypadDelegate类的继承关系如下图所示。

 

布景层类CCLayer和其子类继承自CCKeypadDelegate类,因此布景层类和其子类可以使用获得键盘事件的方法。

 

 

1、CCKeypadDelegate类的函数

 

CCKeypadDelegate类的公共函数见下图。

一般的处理方法是,按下返回键时返回之前的页面,按下Menu键时弹出菜单等。

 

 

2、按键监听事件的使用步骤。

 

<1> 首先使用CCKeypadDelegate接口。CCLayer默认使用CCKeypadDelegate接口,所以其子类不需要再次使用此

接口。

<2> 重写两个按键的回调函数:

virtual void keyBackClicked();    virtual void keyMenuClicked();


<3> setKeypadEnabled(true)设置按键为可操作。

 

 

 

二、按键事件项目实例

 

1、首先新建Cocos2D-X项目,取名为“MyKeypad”,然后在HelloWorldScene.h文件中声明如下成员函数和变量。

class HelloWorld : public cocos2d::CCLayer{public:    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone    virtual bool init();      // there's no 'id' in cpp, so we recommand to return the exactly class pointer    static cocos2d::CCScene* scene();        virtual void keyBackClicked();    virtual void keyMenuClicked();       // implement the "static node()" method manually    CREATE_FUNC(HelloWorld);private:cocos2d::CCLabelTTF*  m_pLabel;};


2、在HelloWorldScene.cpp文件中的init函数中添加如下所示代码。

bool HelloWorld::init(){    bool bRet = false;    do     {        CC_BREAK_IF(! CCLayer::init());        CCSize s = CCDirector::sharedDirector()->getWinSize();CCLabelTTF* label = CCLabelTTF::create("Keypad Test", "Arial", 28);addChild(label, 0);label->setPosition( ccp(s.width/2, s.height-50) );setKeypadEnabled(true);// create a label to display the tip stringm_pLabel = CCLabelTTF::create("Please press any key...", "Arial", 22);m_pLabel->setPosition(ccp(s.width / 2, s.height / 2));addChild(m_pLabel, 0);    m_pLabel->retain();        bRet = true;    } while (0);    return bRet;}

 

3、最后在HelloWorldScene.cpp文件中添加如下所示函数。

void HelloWorld::keyBackClicked(){    m_pLabel->setString("BACK clicked!");}void HelloWorld::keyMenuClicked(){    m_pLabel->setString("MENU clicked!");}


 

4、实例运行效果图。

 

 

 

 

源码下载地址

原创粉丝点击