1

几天前我问这个: 如何使用javafx2同时在同一个精灵的屏幕上有多个实例, 并部分解决了阐述jewelsea建议的问题。

我现在有这个障碍:当按下一个键来“发射”子弹时,武器射出子弹的速度和机关枪一样快。我想限制我游戏中英雄的武器可以射出的子弹数量。例如,决定每 0.5 秒发射一次子弹,或者只是在按下一个键时发射子弹,而不是总是有机关枪效果......在我的游戏中,控制“火”效果的程序部分是这样的:

        scene.setOnKeyTyped(new EventHandler<KeyEvent>() {  
            @Override  
            public void handle(KeyEvent event2) {  

            if (event2.getCode()==KeyCode.F); { .........

在我尝试使用 setOnKeyPressed 和 setOnKeyReleased 并获得相同结果之前。那么我可以尝试只射击子弹同时按住“F”键或限制子弹数量吗?提前谢谢你,再见!

4

1 回答 1

0

我通过使用 aTimeline作为计时器并启动它并在按下键和释放键时停止它来完成此操作:

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class KeyEventTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        Scene scene = new Scene(root, 400, 400);

        Duration firingInterval = Duration.millis(500);
        Timeline firing = new Timeline(
                new KeyFrame(Duration.ZERO, event -> fire()),
                new KeyFrame(firingInterval));
        firing.setCycleCount(Animation.INDEFINITE);

        scene.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.F && firing.getStatus() != Animation.Status.RUNNING) {
                firing.playFromStart();
            }
        });

        scene.setOnKeyReleased(event -> {
            if (event.getCode() == KeyCode.F) {
                firing.stop();
            }
        });

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void fire() {
        // dummy implementation:
        System.out.println("Fire!");
    }

    public static void main(String[] args) {
        launch(args);
    }
}

调整它以随时额外限制屏幕上的子弹数量等是相当容易的。

于 2014-10-04T16:20:57.107 回答