glfwSetKeyCallback(window, key_callback)
即可。下面简单介绍回调函数包含的内容。
函数头为void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
,其中,
key
为按键,例如GLFW_KEY_UP,如果敲下的键不能被GLFW识别,比如Play和E-mail,key值就是GLFW_KEY_UNKNOWN;
scancode
是每个平台自定义的表示按键的代码,当key值为GLFW_KEY_UNKNOWN时scancode会被用来识别键,否则scancode会被忽略;另外它可以和key一起用来获得键的名字const char* key_name = glfwGetKeyName(GLFW_KEY_W, 0);
,第二个参数就是scancode。scancode可以通过const int scancode = glfwGetKeyScancode(GLFW_KEY_X);
获得;
action
代表动作类型,有
- GLFW_PRESS:按下
- GLFW_RELEASE: 松开
- GLFW_REPEAT:重复按键
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
// printf("key=%d, scancode=%d, action=%d, mods=%d", key, scancode, action, mods);
if(action == GLFW_RELEASE){
switch (key)
{
case GLFW_KEY_ESCAPE:
case GLFW_KEY_KP_2:
break;
default:
break;
}
}else if(action == GLFW_REPEAT){
}
}
glfwSetKeyCallback(window, key_callback);