回答編集履歴
2
追記
answer
CHANGED
|
@@ -27,4 +27,20 @@
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
```
|
|
30
|
-
これをsetOnKeyPressed、setOnKeyReleasedそれぞれでKeyManager#handleEventを呼んでやり、Timeline内でisPressed(KeyCode.UP) & isPressed(KeyCode.LEFT)としてやれば「左上」を押していると認識できます。ただし、よくある問題としてフォーカスが外れたときに押しっぱなしになったりするので、そのへんの対処は自分で考えてみてください。
|
|
30
|
+
これをsetOnKeyPressed、setOnKeyReleasedそれぞれでKeyManager#handleEventを呼んでやり、Timeline内でisPressed(KeyCode.UP) & isPressed(KeyCode.LEFT)としてやれば「左上」を押していると認識できます。ただし、よくある問題としてフォーカスが外れたときに押しっぱなしになったりするので、そのへんの対処は自分で考えてみてください。
|
|
31
|
+
|
|
32
|
+
```Java
|
|
33
|
+
public static KeyManager keyManager = new KeyManager;
|
|
34
|
+
|
|
35
|
+
// 中略
|
|
36
|
+
root.setOnKeyPressed(event -> keyManager.handleEvent(event));
|
|
37
|
+
root.setOnKeyReleased(event -> keyManager.handleEvent(event));
|
|
38
|
+
|
|
39
|
+
// Timelineの処理の中
|
|
40
|
+
if(keyManager.isPressed(KeyCode.UP)) {
|
|
41
|
+
//上を押されている
|
|
42
|
+
}
|
|
43
|
+
if(keyManager.isPressed(KeyCode.LEFT)) {
|
|
44
|
+
//左を押されている
|
|
45
|
+
}
|
|
46
|
+
```
|
1
追記
answer
CHANGED
|
@@ -5,4 +5,26 @@
|
|
|
5
5
|
* いまのsetOnKeyPressedだけでは「押しっぱなし」を検知できません。setOnKeyReleasedも使う必要があります。
|
|
6
6
|
* boolean型の変数up,down,left,right,shiftを用意し、setOnKeyPressedで各キーに対応したフラグをtrueにし、setOnKeyReleasedでfalseにします
|
|
7
7
|
* 別スレッドで移動計算を行います。
|
|
8
|
-
* Platform.runLaterを使い、コントロールの座標を計算結果に合わせて移動させます
|
|
8
|
+
* Platform.runLaterを使い、コントロールの座標を計算結果に合わせて移動させます
|
|
9
|
+
|
|
10
|
+
#キー管理クラスのサンプル
|
|
11
|
+
なにもテストしてませんので動作は保証しかねますが、やろうとすることはこういうことだと思います。
|
|
12
|
+
```Java
|
|
13
|
+
public class KeyManager {
|
|
14
|
+
private Map<KeyCode, boolean> map = new HashMap<>();
|
|
15
|
+
public void handleEvent(KeyEvent e) {
|
|
16
|
+
switch(e.getEventType()) {
|
|
17
|
+
case KeyEvent.KEY_PRESSED:
|
|
18
|
+
map.put(e.getCode(), false);
|
|
19
|
+
break;
|
|
20
|
+
case KeyEvent.KEY_RELEASED:
|
|
21
|
+
map.put(e.getCode(), true);
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
public boolean isPressed(KeyCode code) {
|
|
26
|
+
return map.containsKey(code)?map.get(code):false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
これをsetOnKeyPressed、setOnKeyReleasedそれぞれでKeyManager#handleEventを呼んでやり、Timeline内でisPressed(KeyCode.UP) & isPressed(KeyCode.LEFT)としてやれば「左上」を押していると認識できます。ただし、よくある問題としてフォーカスが外れたときに押しっぱなしになったりするので、そのへんの対処は自分で考えてみてください。
|