问题描述
当用户按下一个组合键时,我需要获取键的代码以及当前按下了哪些修饰键(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.
这篇关于获取按键代码以及按键时的按键修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!