如何在游戏循环中绘制图形上下文?

时间:2019-07-04 17:19:07

标签: java javafx

我正在制作水果忍者游戏,我想暂停动画计时器一会儿,并在切片时将图像设置为切片的水果图像“ current.getBufferedImages()[1]”,但得到的图像却与此相同未切片的水果“ current.getBufferedImages()[0]”,即使我更改了要在graphicsContext.setImage()中绘制的图像

        public void startGame(Stage primaryStage) throws Exception {
        ga = GameActions.get();
        canvas = new Canvas(1024,683);

        gc = canvas.getGraphicsContext2D();

        timeline = new Timeline(new KeyFrame(Duration.millis(falling), event -> {
            time += falling / 3000;
            IGameObject c = ga.createGameObject();
            drop.add(c);
        }));
        timeline.setCycleCount(4000);
        timeline.play();

        timer = new AnimationTimer() {

            @Override
            public void handle(long arg0) {
                gameUpdate(primaryStage);
            }

        };
        timer.start();
        scene = new Scene(root, 1024, 683);


        root.getChildren().addAll(ivBackground,lblMissed,canvas,back,reset);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

         public void gameUpdate(Stage stage){
        Image k;
        gc.drawImage(background, 300, 300);
        gc.clearRect(0, 0, 1024, 683);
        Iterator<IGameObject> itr = drop.iterator();
        while(itr.hasNext()) {
            IGameObject current = itr.next();
            EventHandler<MouseEvent> e = new EventHandler<MouseEvent>() {

                @Override
                public void handle(MouseEvent event) {
                    if(current.insideBounds(event.getX(), event.getY()))
                        current.slice();
                }

            };
            gc.getCanvas().setOnMousePressed(e);
            if(!current.isSliced()) {
                k = SwingFXUtils.toFXImage(current.getBufferedImages()[0], null);
            }else {
                k = SwingFXUtils.toFXImage(current.getBufferedImages()[1], null);
                if(current.getObjectType().toString().equalsIgnoreCase("dangerousbomb")) {
                    for(int i=0;i<150000;i++) {
                        gc.drawImage(k, current.getXlocation(), current.getYlocation());
                        timer.stop();
                    }
                    timer.start();
                    itr.remove();
                    lives--;
                    lblLives.setText("Lives: " + String.valueOf(lives));
                }else if(current.getObjectType().toString().equalsIgnoreCase("fatalbomb")) {
                    gameOver();
                    break;
                }else if(current.getObjectType().toString().equalsIgnoreCase("specialfruit")) {
                    for(int i=0;i<150000;i++) {
                        gc.drawImage(k, current.getXlocation(), current.getYlocation());
                        timer.stop();
                    }
                    timer.start();
                    itr.remove();
                    score+=5;
                    lblScore.setText("Score: " + String.valueOf(score));
                    if(score >= highestScore) {
                        highestScore = score;
                        ga.saveHighScore(highestScore);
                        lblHighestScore.setText("Highest Score: "+highestScore);
                    }
                }else if(current.getObjectType().toString().equalsIgnoreCase("fruit")) {
                    for(int i=0;i<150000;i++) {
                        gc.drawImage(k, current.getXlocation(), current.getYlocation());
                        timer.stop();
                    }
                    timer.start();
                    itr.remove();
                    score++;
                    lblScore.setText("Score: " + String.valueOf(score));
                    if(score >= highestScore) {
                        highestScore = score;
                        ga.saveHighScore(highestScore);
                        lblHighestScore.setText("Highest Score: "+highestScore);
                    }
                }
            }

            gc.drawImage(k, current.getXlocation(), current.getYlocation());
            ga.updateObjectsLocations(time,current);


            }
        }
    }

1 个答案:

答案 0 :(得分:2)

gameUpdate在JavaFX应用程序线程上执行。这意味着此方法返回的任何延迟都会简单地冻结GUI,直到该方法返回为止。因此,那些

for(int i=0;i<150000;i++) {
    gc.drawImage(k, current.getXlocation(), current.getYlocation());
    timer.stop();
}

循环不起作用。

最简单的“暂停”方法是节省AnimationTimer继续执行的时间。

timer = new AnimationTimer() {

    @Override
    public void handle(long arg0) {
        gameUpdate(arg0);
    }

};
private long pauseEnd = 0L;

/**
 * Continue updates after a certain number of milliseconds after the current time
 */
private void pauseFor(long currentTime, long durationMillis) {
    pauseEnd = currentTime + 1_000_000L * durationMillis;
}

public void gameUpdate(long timestamp) {
    if (timestamp >= pauseEnd) { // only redraw, if not paused
        ...

        //for(int i=0;i<150000;i++) {
        //    gc.drawImage(k, current.getXlocation(), current.getYlocation());
        //    timer.stop();
        //}
        //timer.start();
        //itr.remove();
        //score++;
        gc.drawImage(k, current.getXlocation(), current.getYlocation());
        itr.remove();
        score++;
        pauseFor(timestamp, 3000); // start updates again in 3000 ms

        ...
    }
}

此外,您需要在游戏循环的每次迭代中为每个游戏对象替换EventHandler。这样,仅检查单个游戏对象与鼠标的交点。您需要使用单个事件处理程序检查所有这些内容。除了从gameLoop方法中删除事件处理程序注册之外,还向start方法中添加以下代码以检查所有对象的交集:

canvas.setOnMousePressed(event -> {
    for (IGameObject current : drop) {
        if(current.insideBounds(event.getX(), event.getY())) {
            current.slice();
        }
    }
});

此外,我强烈建议不要在游戏循环的每次迭代中都一次又一次地转换BufferedImage。最好直接用JavaFX BufferedImage替换Image或保留包含每个转换结果的Map<BufferedImage, Image> ...