在2D JavaFX游戏中让玩家自由移动的关键是通过键盘事件监听来控制角色的移动。以下是一个实现自由移动的基本步骤:
下面是一个示例代码:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.animation.TranslateTransition;
public class Game extends Application {
private static final int PLAYER_SIZE = 50;
private static final int PLAYER_SPEED = 5;
private ImageView playerView;
private TranslateTransition translateTransition;
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 800, 600);
// 创建角色图像
Image playerImage = new Image("player.png");
playerView = new ImageView(playerImage);
playerView.setFitWidth(PLAYER_SIZE);
playerView.setFitHeight(PLAYER_SIZE);
playerView.setX(scene.getWidth() / 2 - PLAYER_SIZE / 2);
playerView.setY(scene.getHeight() / 2 - PLAYER_SIZE / 2);
// 创建角色移动动画
translateTransition = new TranslateTransition(Duration.millis(100), playerView);
translateTransition.setCycleCount(1);
root.getChildren().add(playerView);
// 添加键盘事件监听器
scene.setOnKeyPressed(this::handleKeyPressed);
scene.setOnKeyReleased(this::handleKeyReleased);
primaryStage.setScene(scene);
primaryStage.setTitle("2D JavaFX Game");
primaryStage.show();
}
private void handleKeyPressed(KeyEvent event) {
KeyCode keyCode = event.getCode();
// 根据按下的键盘按键来控制角色移动
switch (keyCode) {
case UP:
moveUp();
break;
case DOWN:
moveDown();
break;
case LEFT:
moveLeft();
break;
case RIGHT:
moveRight();
break;
}
}
private void handleKeyReleased(KeyEvent event) {
KeyCode keyCode = event.getCode();
// 松开键盘按键停止移动
switch (keyCode) {
case UP:
case DOWN:
stopVerticalMove();
break;
case LEFT:
case RIGHT:
stopHorizontalMove();
break;
}
}
private void moveUp() {
translateTransition.stop();
translateTransition.setToY(playerView.getY() - PLAYER_SPEED);
translateTransition.play();
}
private void moveDown() {
translateTransition.stop();
translateTransition.setToY(playerView.getY() + PLAYER_SPEED);
translateTransition.play();
}
private void moveLeft() {
translateTransition.stop();
translateTransition.setToX(playerView.getX() - PLAYER_SPEED);
translateTransition.play();
}
private void moveRight() {
translateTransition.stop();
translateTransition.setToX(playerView.getX() + PLAYER_SPEED);
translateTransition.play();
}
private void stopVerticalMove() {
translateTransition.stop();
translateTransition.setToY(playerView.getY());
translateTransition.play();
}
private void stopHorizontalMove() {
translateTransition.stop();
translateTransition.setToX(playerView.getX());
translateTransition.play();
}
public static void main(String[] args) {
launch(args);
}
}
这个示例代码中,玩家可以通过上、下、左、右方向键来控制角色的移动,每次按下方向键时,角色都会以一定的速度在对应的方向上移动。
请注意,此示例只是简单实现了玩家在2D JavaFX游戏中的自由移动,并不包含完整的游戏逻辑和碰撞检测等功能。在实际开发中,您可能需要根据游戏需求进行相应的扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云