Java Paint 组件刷新率?

标签 java swing animation buffer

我正在用 Java 开发一个小游戏,并且正在重写玩家移动系统,使其不再基于网格。它是一个 2D 横向卷轴游戏,我想要实现的是基本的玩家移动,这样当用户按下并按住右键时,玩家就会向右移动,左键也是如此。我遇到的问题是另一个类中的 Paint 组件在屏幕上绘制播放器的图像,位置 X 和 Y 存储在设置类中。然后,当用户按下 Right 时,KeyListener 类会获取,并添加到 X 值(对于 Left 也是如此,但每次都会减 1)。这会在屏幕上创建一个缓慢移动的角色,我想做的是让他移动得更快,但每次不要添加超过 1 像素,因为看起来他正在跳过像素(我已经尝试过)。

我想知道是否有更好的方法来解决这个问题,因为我使用的代码是最低限度的,我的结果将是一个平滑移动的玩家。

KeyListener 片段:

public void keyPressed(KeyEvent arg0) {
    int key = arg0.getKeyCode();

    if(key == 39) { // Right Key
        Settings.player_pos_x++;
    }else if(key == 37) { // Left Key
        Settings.player_pos_x--;
    }

    main.Game.redo();
}

在屏幕上绘制用户:

g.drawImage(player_image, Settings.player_pos_x, Settings.player_pos_y, this);

感谢您的帮助,如果您需要更多信息或代码,请随时询问。

最佳答案

让我们再试一次:)

双缓冲

报价:http://msdn.microsoft.com/en-us/library/b367a457.aspx

Flicker is a common problem when programming graphics. Graphics operations that require multiple complex painting operations can cause the rendered images to appear to flicker or have an otherwise unacceptable appearance.

When double buffering is enabled, all paint operations are first rendered to a memory buffer instead of the drawing surface on the screen. After all paint operations are completed, the memory buffer is copied directly to the drawing surface associated with it. Because only one graphics operation is performed on the screen, the image flickering associated with complex painting operations is eliminated.

报价:http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

Suppose you had to draw an entire picture on the screen, pixel by pixel or line by line. If you were to draw such a thing directly to the screen (using, say, Graphics.drawLine), you would probably notice with much disappointment that it takes a bit of time. You will probably even notice visible artifacts of how your picture is drawn. Rather than watching things being drawn in this fashion and at this pace, most programmers use a technique called double-buffering.

关于Java Paint 组件刷新率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10252889/

相关文章:

java - @ViewScoped 在开发模式下工作,但在生产模式下不起作用

java - (Java) 类里面的困难

html - CSS3动画——两个问题

java - Eclipse:Struts 2 应用程序中的重构功能。可能的?

java - 我可以创建 Web 应用程序以在没有互联网的情况下在智能手机上使用吗?如何?

java - 在 JTable 的单列上显示 MySQL 数据库中的图像

android - viewflipper仅下一个动画

javascript - 不明白为什么我收到未定义的错误

java - JFrame布局管理

java - 为什么 JLabel 不显示下划线字符?