键盘输入
在 GameMaker 中处理键盘时,您可以使用多种函数来识别不同的键盘状态,例如按下或释放。还有一些将所有按键存储为字符串,或者可以告诉您最后按下的按键是什么,以及其他允许您完全清除键盘状态的按键。
一个键 (或多个键) 的每个输入字符均由其 UTF-8 代码定义,该代码是一个数值。使用 ord 函数可以检索任何角色的该值,但是,GameMaker 还为最常用的键盘特殊键和特殊函数提供了一系列 常量 。通常,您会结合使用 ord 和 keyboard_check* 函数,如下所示:
if (keyboard_check(ord("A")))
{
hspeed = -5;
}
因此,上面的代码将检查 "A" 键,如果按下它,则会将对象的水平速度设置为 -5。请注意,只有当输入字符串长度只有一个字符并且是 0 到 9 之间的数字或从 A 到 大写 的罗马字符时,以这种方式使用 ord 才能正确运行 Z。函数 ord 将返回完整的 UTF-8 值,但 keyboard_check* 函数将 仅检测 A - Z 和 0 - 9。
但是如果您想使用箭头键怎么办?或者如果您想使用 "Shift" 键修改操作?嗯,为此,GameMaker 有一系列 vk_* 常量 (vk_ 代表 虚拟键 ),您可以使用它们来代替 ord:
虚拟键常量 (vk_*)常量 | 描述 |
---|
vk_nokey | keycode representing that no key is pressed |
vk_anykey | keycode representing that any key is pressed |
vk_left | keycode for the left arrow key |
vk_right | keycode for the right arrow key |
vk_up | keycode for the up arrow key |
vk_down | keycode for the down arrow key |
vk_enter | enter key |
vk_escape | escape key |
vk_space | space key |
vk_shift | either of the shift keys |
vk_control | either of the control keys |
vk_alt | alt key |
vk_backspace | backspace key |
vk_tab | tab key |
vk_home | home key |
vk_end | end key |
vk_delete | delete key |
vk_insert | insert key |
vk_pageup | pageup key |
vk_pagedown | pagedown key |
vk_pause | pause/break key |
vk_printscreen | printscreen/sysrq key |
vk_f1 ... vk_f12 | keycode for the function keys F1 to F12 |
vk_numpad0 ... vk_numpad9 | number keys on the numeric keypad |
vk_multiply | multiply key on the numeric keypad |
vk_divide | divide key on the numeric keypad |
vk_add | add key on the numeric keypad |
vk_subtract | subtract key on the numeric keypad |
vk_decimal | decimal dot keys on the numeric keypad |
vk_lshift | left shift key |
vk_lcontrol | left control key |
vk_lalt | left alt key |
vk_rshift | right shift key |
vk_rcontrol | right control key |
vk_ralt | right alt key |
以下是如何使用 vk_* 常量的小示例:
if (keyboard_check_pressed(vk_tab))
{
instance_create_layer(x, y, "Controllers", obj_Menu);
}
上述代码将检测是否 按下了 "Tab" 键,如果按下则创建对象 obj_Menu 的实例。
如果您需要检查不是 0 - 9、A - Z 或 vk_* 常量之一的关键字符,那么您应该检查 keyboard_* 变量之一,例如 keyboard_lastchar 例如:
var _key = keyboard_lastchar;
if ord(_key) == ord("ç")
{
show_debug_message("ç key pressed");
}
功能参考
常规
注意 使用屏幕上的虚拟键盘时,这些函数不会起作用。
模拟按键
注意 使用 虚拟键盘 时仅 keyboard_string 变量会随键盘输入而更新。