为 2D 游戏开发绘制 JPanel 的适当方法? [英] Appropriate way to draw to a JPanel for 2D Game development?

查看:27
本文介绍了为 2D 游戏开发绘制 JPanel 的适当方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个 2D 游戏,但我无法找到使用 BufferStrategy 绘制到 2D Surface/Canvas 的最佳和最有效的方法.我将使用 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.

在其他情况下,您需要构建一个所谓的游戏循环,您可以在其中及时更新游戏状态并渲染更新后的游戏状态.可以在此处找到有关使用 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/

这篇关于为 2D 游戏开发绘制 JPanel 的适当方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆