如何改善2D渲染代码的性能?

时间:2020-11-09 14:34:13

标签: java swing canvas bufferedimage frame-rate

我正在开发一个简单的2D游戏引擎。我完成了渲染器,但是我认为它的表现还不错。我有一个gameScene类,目前仅是gameElement对象数组的包装器,这些对象包含图像以及有关其在屏幕上的位置及其尺寸的信息。我循环遍历数组以在屏幕上绘制这些元素。

如果我绘制一张800 * 600的图像,我将获得68 FPS,这是可以接受的,但我不知道这样是否可以。如果我必须循环遍历数组以绘制100个左右的元素,性能会下降很多。我可以用更有效的方式编写它吗?还是我的FPS计数有误?我应该将渲染器放置在游戏循环中还是放置在paint子类的重写的Canvas方法中?

public class Game {
    public void loop(double fps) {
        JFrame gameFrame = new JFrame();
        Scene gameScene = new Scene(1);
    
        String path = "PATH_TO_IMAGE";
        //POPULATE GAMESCENE
        for (int i = 0; i < 1; i++) {
            for (int j = 0; j < 1; j++) {
                int width = 800;
                int height = 600;
                gameScene.addElement(new GameElement(path, i*width, j*height));
            }
        }
    
        Canvas canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(800, 600));
        gameFrame.add(canvas);
        gameFrame.pack();
        gameFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        gameFrame.setVisible(true);
        canvas.createBufferStrategy(2);
        BufferStrategy bs = canvas.getBufferStrategy();
        BufferedImage canvasImage = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
        int[] imagePixels = ((DataBufferInt) canvasImage.getRaster().getDataBuffer()).getData();
    
        double frameTime = 1.0 / fps;
        double scale = 1000000000;
        double lastTime = System.nanoTime() / scale;
        int frames = 0;
        double seconds = 0;       
    
        while (true) {
            double newTime = System.nanoTime() / scale;
            if (newTime - lastTime >= frameTime) {
            
                //RENDERING CODE
                for (GameElement elem : gameScene.getElements()) {
                    int[] elemPixels = null;
                    BufferedImage im = elem.getImage();
                    int x = elem.getX();
                    int y = elem.getY();
                    elemPixels = im.getRGB(0, 0, im.getWidth(), im.getHeight(), null, 0, im.getWidth());
                    for (int i = 0; i < im.getHeight(); i++) {
                        for (int j = 0; j < im.getWidth(); j++) {
                            if (x + j < 800 && y + i < 600) { 
                                imagePixels[800 * (i + y) + j + x] = elemPixels[im.getWidth() * i + j];
                            }
                        }
                    }
                }
                bs.getDrawGraphics().drawImage(canvasImage, 0, 0, null);
                bs.show();
            
                frames += 1;
                seconds += (newTime - lastTime);
                if (seconds >= 1.0) {
                    double FPS = frames / seconds;
                    System.out.println(FPS);
                    seconds = 0;
                    frames = 0;
                }
                lastTime = newTime;
            }
        }
    }
}

0 个答案:

没有答案