本文介绍了吸引JPanel进行2D游戏开发的合适方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作2D游戏,但是我找不到使用BufferStrategy绘制2D曲面/画布的最佳,最有效方法.我将使用JFrame作为主窗口,并希望绘制到其表面.我希望看到一些有关如何完成此操作的示例代码(如果这样做是一种很好的方法)以及其他示例.如果有人也可以解释这样做的优点和缺点,那将是很好的.

I am wanting to make a 2D Game but I am having trouble finding the best and most efficient way to draw to a 2D Surface/Canvas using a BufferStrategy. I will be using a JFrame as the main window and want to draw to the surface of that. I would love to see some example code of how this is done (if this is a good way to do it) aswell as other examples. It would be great if someone could also explain some advantages and disadvantages of doing so.

我目前正在使用'frame.add(new Painter());'将绘图类添加到JFrame中.然后覆盖paintComponent方法.我发现的唯一问题是似乎只调用了一次此方法.

I am currently adding my drawing class to my JFrame using 'frame.add(new Painter());' and then overriding the paintComponent method. The only problem I have found with this is it seems to only call this method once.

这是我的Painter类:

this is my Painter class:

public class Painter extends JPanel{

    public static Player player;

    public Painter() {
        player = new Player(300, 300);

    }

    public void paint(Graphics g) {
        player.x++;
        g.setColor(Color.white);
        g.fillRect(player.x, player.y, 32, 32);
    }

}

推荐答案

在最简单的情况下,您的游戏仅需要根据用户操作来更新屏幕,则需要调用 repaint()(例如,在JFrame上)进行更新.

In the simplest case, where your game needs to update the screen based on user actions only, you will need to call repaint() (on the JFrame for instance) when you update something.

在其他情况下,您需要构建一个所谓的 Game Loop ,在其中您可以更新游戏状态并及时呈现更新的游戏状态.可以在这里找到有关使用Java代码的简单游戏循环的不错的教程: http://obviam.net/index.php/the-android-game-loop/

In other cases, you need to construct a so called Game Loop, where you update the game state and render updated game state in a timely manner. A nice tutorial on a simple Game Loop with Java code can be found here: http://obviam.net/index.php/the-android-game-loop/

如果您要开发一款严肃的游戏,则应该坚持使用游戏引擎来管理游戏循环和其他常规游戏开发方面的内容.一个好的Java游戏引擎可以在这里找到: http://code.google.com/p/playn/

In case you develop a serious game, you should stick with a game engine for managing the game loop and other routine game development aspects. A good Java game engine can be found here: http://code.google.com/p/playn/

这篇关于吸引JPanel进行2D游戏开发的合适方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 05:57