当用户按下组合键时,我需要获取键的代码以及哪些修饰键(Ctrl
、Alt
、Shift
等)当前被按下,并据此选择适当的反应.有比以下更清洁的方法吗?(使用 InputProcessor#keyDown):
When a user presses a key combination, I need to get key's code and which modifier keys (Ctrl
, Alt
, Shift
etc) are currently pressed, and choose an appropriate reaction based on that. Is there a cleaner way to do this than the following? (using InputProcessor#keyDown):
public boolean keyDown(int keycode) {
boolean ctrl, alt, shift, ...;
if (Gdx.input.isKeyPressed(Input.Keys.LEFT_SHIFT) || Gdx.input.isKeyPressed(Input.Keys.RIGHT_SHIFT)) {
shift = true;
} else if (/* same for ctrl */) {
ctrl = true;
} else /* same for other modifiers */ {
//...
}
// Finally, choose an action based on the key combination pressed
if (shift && keycode == Input.Keys.A) {
// What to do if Shift+A is pressed
} else if (/* and so on */) {
//...
}
}
我看到有 Input.Keys.META_*
位掩码,这可能是我需要的,但我没有找到任何关于如何使用这些位掩码的示例.
I see there are Input.Keys.META_*
bitmasks, which are probably what I need, but I haven't found any example on how to use those.
您可以使用 keyDown()
方法来检测是否按下了 shift(或任何其他修饰键)以及 keyUp()
方法是否再次释放:
You could use the keyDown()
method to detect whether the shift (or any other modifier key) is pressed and the keyUp()
method whether it is released again:
class MyInputProcesses extends InputProcesses {
boolean shift = false;
// etc...
public boolean keyDown(int keycode) {
switch(keycode) {
case Input.Keys.LEFT_SHIFT :
case Input.Keys.RIGHT_SHIFT:
shift = true;
break;
case Input.Keys.A:
if(shift) {
// Do something if Shift+A is pressed
}
break;
}
// etc...
}
public boolean keyUp(int keycode) {
switch(keycode) {
case Input.Keys.LEFT_SHIFT :
case Input.Keys.RIGHT_SHIFT:
shift = false;
break;
// etc...
}
}
}
该方法可以防止您询问修饰键的状态,并且更容易修改这些键的触发器(例如,只接受左移).
The approach prevents you asking the states of the modifier keys and it is easier to modify the triggers for these keys (e.g. only accept the left shift).
我猜这个解决方案是否更好/更好是个人喜好.我怀疑这会更快(明显).
Whether this solution is better/nicer is of personal preference I guess. I doubt it that this will be any (noticeable) faster.
这篇关于获取按键代码以及按键修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!