0

我正在用 Java 编写平台游戏。一切正常,没有更大的问题,除了Canvas更新时屏幕上的闪烁。

我将大致解释一下我的游戏“引擎”是如何工作的:在我的主要方法中,我有一个循环,它每秒重复 30 次:

while (play) {
    Date delay_time = new Date();
    delay_time.setTime(delay_time.getTime() + (int) (1000*(1.0/FPS)));

    // Here is all the game stuff, like the motion of the player,
    // function calling, etc.

    Graphics g = can.getGraphics();
    can.update(g);
    while(new Date().before(delay_time)) {

    }

}

我的 FPS 变量static final int当前设置为 30。所以我每秒更新我的 Canvas 30 次。

Play 是一个布尔值,它控制游戏是否仍在进行,或者玩家是否死亡。

Can是我班级的一个实例MyCanvas.java。paint() 方法的代码如下所示:

   if (Main.play) {
       //NOW
       //Draw the now Level Caption
       //SIZE: 240
       g2.setFont(new Font("Bank Gothic", Font.PLAIN, 240));
       g2.setColor(new Color(Math.abs(bg.getRed() - 30), Math.abs(bg.getGreen() - 30), Math.abs(bg.getBlue() - 30)));
       g2.drawString("LEVEL " + Main.lvl, 80, 80 + 300 - Main.groundY);

       //Draw the ground
       g2.setColor(haba);
       g2.fillRect(0, Main.screenSize.height - Main.groundY, Main.screenSize.width, Main.groundY);

       //Draw the level
       g2.setColor(haba);
       for (int i = 0; i < Main.LVLWIDTH; i++) {
            for (int j = 0; j < Main.LVLHEIGHT; j++) {
                if (Main.level[i][j] == '1') {
                    g2.fillRect(i*(Main.BLOCK_X), (j - Main.LVLHEIGHT)*(Main.BLOCK_Y) + Main.screenSize.height - Main.groundY, Main.BLOCK_X, Main.BLOCK_Y);
                }

        }

        //More drawing stuff...

    }

所以,正如你所看到的,我更新了很多 - 每秒 30 次。这导致我的游戏(顺便说一句以全屏模式播放)一直闪烁的问题。如何解决这个问题?缓冲策略是正确的方法吗?如果是,我该怎么做?您能否解释一下 Bufferstartegy 或提供有很好的教程或解释的链接,哪些对技术和非初学者友好?那很好啊。

4

1 回答 1

0

BufferStrategy 类解决了我的问题。这是一个很好的链接,以及如何使用它的制作精良的示例:http:
//docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html

于 2014-06-04T19:05:29.663 回答