Java 2D游戏图形 [英] Java 2D game graphics

查看:105
本文介绍了Java 2D游戏图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下个学期,我们有一个模块在一个团队中制作Java应用程序。模块的要求是制作游戏。在圣诞节假期,我一直在做一些练习,但我无法弄清楚绘制图形的最佳方式。



我使用Java Graphics2D对象在屏幕上绘制形状,并每秒调用 repaint() 30次,但这会非常闪烁。在Java中绘制高性能2D图形有更好的方法吗?

使用BufferStrategy并对其进行渲染,下面的代码应该会告诉你它是如何工作的,我已经从我自己编写的引擎中提取了代码,通过这里

性能完全取决于你想画画,我的游戏大多使用图像。其中约1500人,我仍然在480x480以上200 FPS以上。只有100张图片,我在禁用帧限制时击中了6k FPS。



一个小游戏(这个游戏一次在屏幕上有大约120张图片)可以在这里找到(是的,下面的方法也可以作为一个小程序正常工作。)

  import java.awt.Canvas; 
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
导入javax.swing.WindowConstants;

public class Test extends Thread {
private boolean isRunning = true;
私人画布画布;
私有BufferStrategy策略;
私有BufferedImage背景;
私人Graphics2D backgroundGraphics;
私人Graphics2D图形;
私有JFrame框架;
private int width = 320;
private int height = 240;
private int scale = 1;
private GraphicsConfiguration config =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();

//创建硬件加速镜像
public final BufferedImage create(final int width,final int height,
final boolean alpha){
return config.createCompatibleImage(宽度,高度,alpha
?Transparency.TRANSLUCENT:Transparency.OPAQUE);


//安装
public Test(){
// JFrame
frame = new JFrame();
frame.addWindowListener(new FrameClose());
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.setSize(width * scale,height * scale);
frame.setVisible(true);

// Canvas
canvas = new Canvas(config);
canvas.setSize(width * scale,height * scale);
frame.add(canvas,0);

//背景&缓冲区
background = create(width,height,false);
canvas.createBufferStrategy(2);
do {
strategy = canvas.getBufferStrategy();
} while(strategy == null);
start();
}

private class FrameClose extends WindowAdapter {
@Override
public void windowClosing(final WindowEvent e){
isRunning = false;



//屏幕和缓冲区内容
private Graphics2D getBuffer(){
if(graphics == null){
尝试{
graphics =(Graphics2D)strategy.getDrawGraphics();
} catch(IllegalStateException e){
return null;
}
}
返回图形;
}

私有布尔updateScreen(){
graphics.dispose();
graphics = null;
尝试{
strategy.show();
Toolkit.getDefaultToolkit()。sync();
return(!strategy.contentsLost());

} catch(NullPointerException e){
return true;

} catch(IllegalStateException e){
return true;



public void run(){
backgroundGraphics =(Graphics2D)background.getGraphics();
long fpsWait =(long)(1.0 / 30 * 1000);
main:while(isRunning){
long renderStart = System.nanoTime();
updateGame();

//更新图形
do {
Graphics2D bg = getBuffer();
if(!isRunning){
break main;
}
renderGame(backgroundGraphics); //这将调用你的绘制方法
// thingy
if(scale!= 1){
bg.drawImage(background,0,0,width * scale,height
* scale,0,0,width,height,null);
} else {
bg.drawImage(background,0,0,null);
}
bg.dispose();
} while(!updateScreen());

//最好在这里做一些FPS限制
long renderTime =(System.nanoTime() - renderStart)/ 1000000;
try {
Thread.sleep(Math.max(0,fpsWait - renderTime));
} catch(InterruptedException e){
Thread.interrupted();
休息;
}
renderTime =(System.nanoTime() - renderStart)/ 1000000;

}
frame.dispose();

$ b $ public void updateGame(){
//更新游戏逻辑
}

public void renderGame(Graphics2D g){
g.setColor(Color.BLACK);
g.fillRect(0,0,width,height);


public static void main(final String args []){
new Test();
}
}


Next semester we have a module in making Java applications in a team. The requirement of the module is to make a game. Over the Christmas holidays I've been doing a little practice, but I can't figure out the best way to draw graphics.

I'm using the Java Graphics2D object to paint shapes on screen, and calling repaint() 30 times a second, but this flickers terribly. Is there a better way to paint high performance 2D graphics in Java?

解决方案

What you want to do is to create a canvas component with a BufferStrategy and render to that, the code below should show you how that works, I've extracted the code from my self written Engine over here.

Performance solely depends on the stuff you want to draw, my games mostly use images. With around 1500 of them I'm still above 200 FPS at 480x480. And with just 100 images I'm hitting 6k FPS when disabling the frame limiting.

A small game (this one has around 120 images at once at the screen) I've created can be found here (yes the approach below also works fine as an applet.)

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Test extends Thread {
    private boolean isRunning = true;
    private Canvas canvas;
    private BufferStrategy strategy;
    private BufferedImage background;
    private Graphics2D backgroundGraphics;
    private Graphics2D graphics;
    private JFrame frame;
    private int width = 320;
    private int height = 240;
    private int scale = 1;
    private GraphicsConfiguration config =
            GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice()
                .getDefaultConfiguration();

    // create a hardware accelerated image
    public final BufferedImage create(final int width, final int height,
            final boolean alpha) {
        return config.createCompatibleImage(width, height, alpha
                ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
    }

    // Setup
    public Test() {
        // JFrame
        frame = new JFrame();
        frame.addWindowListener(new FrameClose());
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.setSize(width * scale, height * scale);
        frame.setVisible(true);

        // Canvas
        canvas = new Canvas(config);
        canvas.setSize(width * scale, height * scale);
        frame.add(canvas, 0);

        // Background & Buffer
        background = create(width, height, false);
        canvas.createBufferStrategy(2);
        do {
            strategy = canvas.getBufferStrategy();
        } while (strategy == null);
        start();
    }

    private class FrameClose extends WindowAdapter {
        @Override
        public void windowClosing(final WindowEvent e) {
            isRunning = false;
        }
    }

    // Screen and buffer stuff
    private Graphics2D getBuffer() {
        if (graphics == null) {
            try {
                graphics = (Graphics2D) strategy.getDrawGraphics();
            } catch (IllegalStateException e) {
                return null;
            }
        }
        return graphics;
    }

    private boolean updateScreen() {
        graphics.dispose();
        graphics = null;
        try {
            strategy.show();
            Toolkit.getDefaultToolkit().sync();
            return (!strategy.contentsLost());

        } catch (NullPointerException e) {
            return true;

        } catch (IllegalStateException e) {
            return true;
        }
    }

    public void run() {
        backgroundGraphics = (Graphics2D) background.getGraphics();
        long fpsWait = (long) (1.0 / 30 * 1000);
        main: while (isRunning) {
            long renderStart = System.nanoTime();
            updateGame();

            // Update Graphics
            do {
                Graphics2D bg = getBuffer();
                if (!isRunning) {
                    break main;
                }
                renderGame(backgroundGraphics); // this calls your draw method
                // thingy
                if (scale != 1) {
                    bg.drawImage(background, 0, 0, width * scale, height
                            * scale, 0, 0, width, height, null);
                } else {
                    bg.drawImage(background, 0, 0, null);
                }
                bg.dispose();
            } while (!updateScreen());

            // Better do some FPS limiting here
            long renderTime = (System.nanoTime() - renderStart) / 1000000;
            try {
                Thread.sleep(Math.max(0, fpsWait - renderTime));
            } catch (InterruptedException e) {
                Thread.interrupted();
                break;
            }
            renderTime = (System.nanoTime() - renderStart) / 1000000;

        }
        frame.dispose();
    }

    public void updateGame() {
        // update game logic here
    }

    public void renderGame(Graphics2D g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);
    }

    public static void main(final String args[]) {
        new Test();
    }
}

这篇关于Java 2D游戏图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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