本文介绍了JavaFX:使用箭头键和空格键移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作像Space Invaders这样的小游戏。我正在使用JavaFX和Netbeans 6.9并且在其他地方找不到答案,所以我想我只是在这里问。

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.

我有一张太空船的图片,我想用我的箭头键移动。当我按空格键时,它应该射击导弹。导弹可以摧毁陨石。

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.

这是我目前的代码:

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";
            }
        }
    ]
}
}

提前致谢。

推荐答案

您必须将keyListener添加到场景中

You have to add keyListener to your scene

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();
    }
};

这篇关于JavaFX:使用箭头键和空格键移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:43