画布 - 良好的渲染实践?

2022-09-02 22:08:48

我最近在小型Java游戏中经常使用Canvas,我注意到可能会发生很多奇怪的事情。例如,今天早些时候,我创建了一个小游戏,其目标是射击敌舰并获得分数。游戏在屏幕上绘制了32x32的微小图像(有时略大),由于我忘记了的原因,游戏渲染得很奇怪。

例如,我的飞船的头部上方有一个生命值条:

enter image description here

从图像中可以看出,纹理真的很小。尽管如此,游戏还是滞后了,有时事情会像这样错误地呈现,例如:

enter image description here

如果你仔细观察生命值栏的顶部,你可以看到它已经稍微向上移动了,这让我感到困惑的是,当我所有的渲染都被缓冲时,他是如何发生的。

我的渲染代码:

public void render(){
    BufferStrategy bs = getBufferStrategy();
    if(bs == null){
        createBufferStrategy(3);
        return;
    }
    Graphics2D g = (Graphics2D)bs.getDrawGraphics();
    toDrawG.setColor(new Color(0x222222));
    toDrawG.fillRect(0, 0, WIDTH, HEIGHT);
    draw((Graphics2D)toDrawG);
    g.drawImage(toDraw, 0, 0, null);
    g.dispose();
    bs.show();
}

public void draw(Graphics2D g){
    if(Settings.planets){
    renderer.renderPlanets();
    }
    if(level != null){
    for(int i = 0 ; i < level.entityList.size(); i++){
        if(level.entityList.get(i) != null){
        level.entityList.get(i).render(renderer);
        }
        }
    }
    renderer.overlayString("Space Game", 20, 20, 24, 0xFFFFFF);
    renderer.overlayString(VERSION, 20, 50, 24, 0xFFFFFF);
    renderer.overlayString("FPS: " + renderer.fps, 20, 70, 24, 0xFFFFFF);
    renderer.overlayString("Ships spawned: " + level.shipsSpawned, 20, 90, 24,     0xFFFFFF);
    renderer.overlayString("Time Survived: " + level.time / 100 + "s", 20, 110,     24, 0xFFFFFF);
    renderer.overlayString("Physics FPS: " + fps, 20, 130, 24, 0xFFFFFF);

    if(currentGui != null){
        currentGui.render(renderer);
    }else{
        map.drawMinimap(SpaceGame.WIDTH-Minimap.WIDTH-20, SpaceGame.HEIGHT-    Minimap.HEIGHT-30);
    }

}

我的“渲染.class”,如果你需要研究它:

package com.maestrum;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.util.Random;

public class Render implements Runnable{

public Graphics2D g2d;

public double xScroll,yScroll;

public int frames;
public int fps;
public long lastTime;

public int[] pSequence = new int[40];   
public SpaceGame game;

public Entity trackedEntity;

public Random rand;

public Render(SpaceGame game, Graphics2D g){
    this.game = game;
    this.g2d = g;
    this.rand = new Random();
    for(int i = 0 ; i < 40; i++){
        pSequence[i] = rand.nextInt(15) + 1;
    }
}

@Override
public void run() {     
    renderLoop();
}

public void renderLoop(){
    while(true){
        game.render();
        if(System.currentTimeMillis() - lastTime >= 1000){
            fps = frames;
            frames = 0;
            lastTime = System.currentTimeMillis();
        }
        frames++;
    }
}

public void renderPlanets(){
    overlayImage(ImageHandler.background, 0, 0, 1.5);
    for(int i = 0 ; i < 20; i++){
        overlayImage(ImageHandler.planets[pSequence[i]/4][pSequence[i]%4], i * 400 - xScroll/pSequence[i], i * pSequence[i]*40 - yScroll/pSequence[i]*2, pSequence[i]);
    }
}

private class PlanetRenderer {



}

public void overlayString(String s, double x, double y, int fontSize, int colour){
    drawString(s, x+xScroll, y+yScroll, fontSize, colour);
}

public void overlayRectangle(double x, double y, int xs, int ys, int colour){
    drawRectangle(x+xScroll, y+yScroll, xs, ys, colour);
}

public void overlayBlurred(BufferedImage img, double x, double y, double scale){
    drawImageBlurred(img, x+xScroll, y+yScroll, scale);
}

public void overlayImage(BufferedImage img, double x, double y, double scale){
    drawImage(img, x+xScroll, y+yScroll, scale);
}

public BufferedImage execute(BufferedImage img) {
    // TODO Auto-generated method stub
    float weight = 1.0f/2.0f;

    float [] elements = {weight, weight, weight, weight, weight, weight, weight, weight, weight};

    Kernel k = new Kernel (3,3,elements);
    ConvolveOp op = new ConvolveOp(k);

    BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());

    op.filter(img, dest);
    return dest;
}

public void drawImageBlurred(BufferedImage img, double x, double y, double scale){
    x -= xScroll;
    y -= yScroll;
    BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null);
    execute(image);
    g2d.drawImage(image, (int)x, (int)y, null);
    g.dispose();
}

public void drawString(String s, Vector2D pos, int fontSize, int colour){
    drawString(s, pos.x, pos.y, fontSize, colour);
}

public void drawString(String s, double x, double y, int fontSize, int colour){
    if(s == null){
        return;
    }
    x -= xScroll;
    y -= yScroll;
    BufferedImage img = new BufferedImage(s.length()*fontSize+1, fontSize*2, BufferedImage.TYPE_INT_ARGB);
    Graphics g = img.getGraphics();
    g.setColor(new Color(colour));
    g.setFont(new Font("Consolas", Font.BOLD, fontSize));
    g.drawString(s, 0, img.getHeight()/2);
    g2d.drawImage(img, (int)x, (int)y, null);
    g.dispose();
}

public void drawImage(BufferedImage img, Vector2D pos, double scale){
    drawImage(img, pos.x, pos.y, scale);
}

public void drawLine(Vector2D v1, Vector2D v2, int colour, int width){
    drawLine(v1.x, v1.y, v2.x, v2.y, colour, width);
}

public void drawLine(double x1, double y1, double x2, double y2, int colour, int lWidth){
    x1 -= xScroll;
    y1 -= yScroll;
    x2 -= xScroll;
    y2 -= yScroll;
    g2d.setColor(new Color(colour));
    g2d.setStroke(new BasicStroke(lWidth));
    g2d.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
}

public void drawImage(BufferedImage img, double x, double y, double scale){
    x -= xScroll;
    y -= yScroll;
    BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null);
    g2d.drawImage(image, (int)x, (int)y, null);
    g.dispose();
}

public void drawRectangle(Vector2D pos, int xs, int ys, int colour){
    drawRectangle(pos.x, pos.y, xs, ys, colour);
}

public void drawRectangle(double x, double y, int xs, int ys, int colour){
    if(xs <= 0){
        return;
    }
    x -= xScroll;
    y -= yScroll;
    BufferedImage image = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(new Color(colour));
    g.fillRect(0, 0, xs, ys);
    g2d.drawImage(image, (int)x, (int)y, null);
    g.dispose();
}

public void drawImageRotated(BufferedImage img, Vector2D pos, double scale, double angle) {
    drawImageRotated(img, pos.x, pos.y, scale, angle);
}

 public void drawImageRotated(BufferedImage img, double x, double y, double scale, double angle) {
        x -= xScroll;
        y -= yScroll;  
        BufferedImage image = new BufferedImage((int)(img.getWidth() * 1.5D), (int)(img.getHeight() * 1.5D), 2);
        Graphics2D g = (Graphics2D)image.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
        g.drawImage(img, image.getWidth() / 2 - img.getWidth() / 2, image.getHeight() / 2 - image.getHeight() / 2, null);
        g2d.drawImage(image, (int)(x-image.getWidth()*scale/2), (int)(y-image.getHeight()*scale/2), (int)(image.getWidth()*scale), (int)(image.getHeight()*scale), null);
        g.dispose();      
 }

}

正如您在渲染类中看到的,渲染过程每秒完成尽可能多的次。这是为了给游戏提供尽可能高的FPS。如果你错过了我问的重点;在使用 Java 渲染内容时,我应该考虑哪些好的做法?而且,是什么可能导致太空飞船的生命值条变成这样?

注意:看看这个视频,我运行了该程序,并获得了80FPS和50000个粒子,但是使用我的渲染代码(显然质量要低得多),在事情开始混乱之前,我只能渲染100个左右的粒子。

http://www.youtube.com/watch?v=6M3Ze4Eu87Y

这是我的 tick() 函数,每次游戏 tick (10ms) 都会被调用

public void tick(){
    if(System.currentTimeMillis() - lastTime >= 1000){
        fps = frames;
        frames = 0;
        lastTime = System.currentTimeMillis();
    }
    frames++;
    if(renderer.trackedEntity != null){
        renderer.xScroll = renderer.trackedEntity.pos.x-SpaceGame.WIDTH/2;
        renderer.yScroll = renderer.trackedEntity.pos.y-SpaceGame.HEIGHT/2;
    }
    if(level != null && !paused){
        level.tick();
    }
    if(currentGui != null && currentGui.pausesGame()){
        paused = true;
    }else{
        paused = false;
    }
}

答案 1

我认为@mantrid的答案应该解决您的问题。就性能而言...在你的代码中有一些明显的“罪”:

不要将图像绘制到图像中以绘制图像

public void drawImage(BufferedImage img, double x, double y, double scale){
    x -= xScroll;
    y -= yScroll;
    BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null);
    g2d.drawImage(image, (int)x, (int)y, null);
    g.dispose();
}

我看不出这有什么意义。为什么不这样做:

public void drawImage(BufferedImage img, double x, double y, double scale){
    g2d.drawImage(img, (int)(x-xScroll), (int)(y-yScroll), (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null);
}

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

下一个实际上烧伤了我的眼睛

public void drawRectangle(double x, double y, int xs, int ys, int colour){
    if(xs <= 0){
        return;
    }
    x -= xScroll;
    y -= yScroll;
    BufferedImage image = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(new Color(colour));
    g.fillRect(0, 0, xs, ys);
    g2d.drawImage(image, (int)x, (int)y, null);
    g.dispose();
}

为什么?这更简单,更快捷:

public void drawRectangle(double x, double y, int xs, int ys, int colour){
    if(xs <= 0)
        return;

    g2d.setColor(new Color(colour));
    g2d.fillRect((int)(x-xScroll), (int)(y-yScroll), xs, ys);
}

和 也是如此。只需直接绘制到g2d缓冲区,您害怕什么?drawImageRotateddrawString

绘制图像模糊

首先。。。你又在这样做了!第二:您似乎正在对每帧上的图像应用卷积操作,为什么不只执行一次该操作(例如,在应用程序开始时,或者更好的是,在图像编辑程序中)。

我的意思一点也不差,但你显然对编程一般来说不是很有经验。我想你可以看看处理(http://processing.org)。我在这里有点偏见,因为我几乎每天都在使用它。这是一个很好的学习和原型设计环境,用java编写,应该让你停止考虑实现细节(比如翻转缓冲区),专注于你真正关心的东西(制作一个游戏!

好吧,希望我说的有道理。祝您编码好运!:)


答案 2

运行状况栏可能会移动,因为当游戏滞后时,并且会在组件/叠加层仍呈现到后台缓冲区时进行更新。要解决此问题,请执行以下操作:xScrollyScroll

1)按比例移动游戏对象,以达到最新更新所经过的时间,以保持游戏速度始终恒定。向和所有游戏对象添加参数更新方法deltalevel.tick()

2)放入和相同的循环序列中,以确保游戏对象首先更新:level.tick()game.render()

currentTime = System.currentTimeMillis();
delta = currentTime - lastTime; 

if(level != null && !paused){
    level.tick(delta); // introduce delta here
    game.render();
}

lastTime = currentTime;

通常,请考虑以下附加步骤:

1) 设置为加快渲染速度Component.setIgnoreRepaint(true)

2)优化图像以在开始时显示当前

GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
Image optimized = gc.createCompatibleImage(img.getWidth(),img.getHeight(),Transparency.BITMASK);
optimized.getGraphics().drawImage(unoptimized, 0, 0, null);

推荐