JavaFX:使用箭头键和空格键移动图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22014950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX: Moving image with arrow keys and spacebar
提问by Lampe
I'm trying to make a little game like Space Invaders. I'm using JavaFX with Netbeans 6.9 and couldn't find an answer elsewhere, so I thought I'ld just ask here.
我正在尝试制作一个像 Space Invaders 这样的小游戏。我将 JavaFX 与 Netbeans 6.9 一起使用,但在其他地方找不到答案,所以我想我只是在这里问一下。
I have an image of a space ship, which I would like to move using my arrow keys. When I press spacebar it should shoot a missile. The missile can destroy a meteorite.
我有一张太空船的图像,我想使用箭头键移动它。当我按空格键时,它应该发射导弹。导弹可以摧毁陨石。
Here's my current code:
这是我当前的代码:
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.animation.Timeline;
import javafx.animation.Interpolator;
var x: Number;
Timeline {
repeatCount: Timeline.INDEFINITE
autoReverse: true
keyFrames: [
at (0s) {x => 500.0},
at (10s) {x => -100.0 tween Interpolator.LINEAR}
]
}.play();
Stage {
title: "Shoot"
scene: Scene {
fill: Color.BLACK
width: 800
height: 500
content: [
ImageView {
x: 500 y: 25
image: Image {
url: "{__DIR__}earth.jpg";
}
}
ImageView {
translateX: bind x
x: 150 y: 300
image: Image {
url: "{__DIR__}meteorite.png";
}
}
ImageView {
x: 400 y: 450
image: Image {
url: "{__DIR__}spaceship.png";
}
}
]
}
}
Thanks in advance.
提前致谢。
回答by ItachiUchiha
You have to add keyListener to your scene
您必须将 keyListener 添加到您的场景中
private EventHandler<KeyEvent> keyListener = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.UP || event.getCode() == KeyCode.DOWN ||
event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT) {
//your code for moving the ship
}
else if(event.getCode() == KeyCode.SPACE) {
//your code for shooting the missile
}
event.consume();
}
};