簡體   English   中英

JavaFX的平穩運行和時間表

[英]JavaFX smooth movement and timelines

我最近開始使用JavaFX,並且正在通過WASD按鍵控制玩家制作一款小型游戲。 首先,我做到了,這樣您就可以通過在keyPress上調整他的x和y坐標來移動播放器,但是我發現移動非常粗糙。 現在,我更改了內容並開始使用時間軸來啟動和停止,並在按下和釋放鍵時停止它們。

編碼:

Timeline timelineW = new Timeline();
Timeline timelineA = new Timeline();
Timeline timelineS = new Timeline();
Timeline timelineD = new Timeline();

 public void createTimeLineW() {
    timelineW.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineW.getKeyFrames().add(kf);
}

public void createTimeLineA() {
    timelineA.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineA.getKeyFrames().add(kf);
}

public void createTimeLineS() {
    timelineS.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineS.getKeyFrames().add(kf);
}

public void createTimeLineD() {
    timelineD.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineD.getKeyFrames().add(kf);
}

這是當前運動的基礎。 因此,在按下W時,imageView播放器將獲得timelineW.play();在釋放W時,它將獲得timelineW.stop();。 其他鍵也一樣 我做出此更改的總體原因是因為運動更加平穩,但仍然存在一些錯誤。 這樣做甚至可以運動嗎? 還是我應該尋找替代方案。

正手謝謝。

通常,您需要定期檢查按鍵並重置移動時間軸:

/** Distance player moves in one "step." */
private static final int movementDistance = 10;

/** Time it takes to move one "step." */
private static final Duration movementTime = Duration.seconds(0.5);

private Timeline xMovement;

private void checkMovementKeys() {
    // ...

    if (xMovement == null) {
        xMovement = new Timeline();
    }

    if (rightMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() + movementDistance)));
        xMovement.playFromStart();
    }
    if (leftMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() - movementDistance)));
        xMovement.playFromStart();
    }

    // ...
}

請注意,循環計數保留默認值,即1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM