Hallo. Ich möchte meinen Schläger (paddle) mit der KeyEvent Methode verwenden, jedoch weiß ich nicht wie sich das mit Canvas verhält. Gilt dasselbe wie bei Scene oder gelten andere Regeln? Ich würde mich über Beispiele sehr freuen. In meinem Fall möchte ich nur eine Plattform nach links mit A bewegen und nach rechts mit D, auf der X Achse entlang.
Java:
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Breakout extends Application {
public static void main(String[] args) {
launch(args);
}
private static final int width = 700;
private static final int height = 900;
private boolean gameStarted;
private int rad = 10;
private int ballYPos = width / 2;
private int ballXPos = height / 2;
private int paddleXpos = width / 2;
private int paddleYpos = height - 100;
private int ballXSpeed = 2;
private int ballYSpeed = 2;
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
Timeline t = new Timeline(new KeyFrame(Duration.millis(10), e -> run(gc)));
t.setCycleCount(Timeline.INDEFINITE);
canvas.setOnMouseClicked(e -> gameStarted = true);
//Canvas mit KeyHandler, den ich verwenden möchte
canvas.setOnKeyPressed(e -> paddleXpos--);
primaryStage.setTitle("Breakout");
primaryStage.setScene(new Scene(new StackPane(canvas)));
primaryStage.show();
t.play();
}
public void run(GraphicsContext gc) {
gc.setFill(Color.GRAY);
gc.fillRect(0, 0, width, height);
gc.setFill(Color.GREEN);
gc.fillOval(ballXPos, ballYPos, rad, rad);
gc.setFill(Color.BLUE);
gc.fillRect(paddleXpos, paddleYpos, 50, 10);
gc.setFill(Color.RED);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
gc.fillRect(j * 130 + 55, i * 30 + 40, 75, 20);
}
}
if (gameStarted) {
ballYPos += ballYSpeed;
ballXPos += ballXSpeed;
if (ballXPos == width - rad || ballXPos == 0) {
ballXSpeed *= -1;
}
if (ballYPos == height - rad || ballYPos == 0) {
ballYSpeed *= -1;
}
}
}
}