cocos2dx 键盘、手机、遥控器等按键响应映射代码


cocos2dx 键盘、手机、遥控器等按键响应映射代码

最近发现cocos各个版本的按键响应都不全,有些按键都没有进行监听和映射,现整理备忘(感谢小亮同学的分享!)

修改依照老版本coco2dx 2.1.4进行,其他版本同理

  1. C++代码修改

cocos2d-x-2.1.4\cocos2dx\keypad_dispatcher\CCKeypadDelegate.h

增加事件处理方法,根据自己的需要添加一个或几个处理方法,如按下处理,抬起处理

1
virtual void onkeyDown(int nMsgType) {};

cocos2d-x-2.1.4\cocos2dx\keypad_dispatcher\CCKeypadDispatcher.cpp

修改dispatchKeypadMSG(ccKeypadMSGType nMsgType)方法:里面原来只监听了返回和菜单两个按键,增加我们需要的其他按键

1
2
3
4
5
6
7
8
9
10
11
switch (nMsgType)
{
case kTypeBackClicked:
pDelegate->keyBackClicked();
break;
case kTypeMenuClicked:
pDelegate->keyMenuClicked();
break;
default:
break;
}

改为:

1
pDelegate->onkeyDown(nMsgType);

cocos2d-x-2.1.4\cocos2dx\platform\win32\CCEGLView.cpp

把Win32的事件派发改为派发所有按键事件,这里只改了按下事件,如果需要抬起事件同理

1
2
3
4
5
6
7
8
9
10
if (wParam == VK_F1 || wParam == VK_F2)
{
CCDirector* pDirector = CCDirector::sharedDirector();
if (GetKeyState(VK_LSHIFT) < 0 || GetKeyState(VK_RSHIFT) < 0 || GetKeyState(VK_SHIFT) < 0)
pDirector->getKeypadDispatcher()->dispatchKeypadMSG(wParam == VK_F1 ? kTypeBackClicked : kTypeMenuClicked);
}
else if (wParam == VK_ESCAPE)
{
CCDirector::sharedDirector()->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked);
}

改为:

1
CCDirector::sharedDirector()->getKeypadDispatcher()->dispatchKeypadMSG(wParam);

cocos2d-x-2.1.4\cocos2dx\platform\android\jni\TouchesJni.cpp

把安卓的事件派发改为派发所有按键事件

1
2
3
4
5
6
7
8
9
10
11
12
switch (keyCode) {
case KEYCODE_BACK:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked))
return JNI_TRUE;
break;
case KEYCODE_MENU:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeMenuClicked))
return JNI_TRUE;
break;
default:
return JNI_FALSE;
}

改为:

1
2
3
4
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(keyCode))
{
return JNI_FALSE;
}
  1. java代码修改

cocos2d-x-2.1.4\cocos2dx\platform\android\java\src\org\cocos2dx\lib\Cocos2dxGLSurfaceView.java

1
2
3
4
5
6
7
8
9
10
11
12
13
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
}
});
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}

改为:

1
2
3
4
5
6
7
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
}
});
return true;
  1. 使用

Win32下的按键code:

1
2
3
4
5
6
7
8
9
UP = 38,//上
DOWN = 40,//下
LEFT = 37,//左
RIGHT = 39,//右
ENTER = 13,//确定
BACK = 27,//返回
1 = 49,//1
2 = 50,//2
3 = 51,//3

遥控器下的按键code:

1
2
3
4
5
6
7
8
9
10
UP = 19,//上
DOWN = 20,//下
LEFT = 21,//左
RIGHT = 22,//右
OK = 23,//确定
BACK = 4,//返回
MENU = 82,//菜单
1 = 8,//1
2 = 9,//2
3 = 10,//3
  • 在需要監聽按鍵的界面

h文件增加

1
virtual void onkeyDown(int wParam);

cpp增加

1
2
3
4
5
void ShopLayer::onkeyDown(int wParam)
{
//根据wParam的值进行处理

}