本系列學習教程使用的是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 string
m_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、執行個體運作效果圖。
源碼下載下傳位址