2

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.

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Lampe
  • 21
  • 1
  • 1
  • 2

1 Answers1

4

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();
    }
};
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
  • I am not very good with the new LAMDA expression, so I am afraid, I can't your current code. If you have a pure java version of the code, I would be happy to edit it ! – ItachiUchiha Feb 26 '14 at 08:51
  • this will give you some idea. You can implement it in javafx http://stackoverflow.com/questions/20485406/how-do-i-move-a-graphic-across-the-screen-with-arrow-keys – ItachiUchiha Feb 26 '14 at 09:06