gpt4 book ai didi

Java 屏幕渲染

转载 作者:行者123 更新时间:2023-12-02 10:25:27 24 4
gpt4 key购买 nike

我正在努力学习 Java 游戏开发,希望有一天能上大学。我目前正在学习教程并学习基础知识。但是,在遵循教程后,我的渲染并未完全渲染,它仅渲染了预期屏幕的一半。以下代码是我使用过的两个类。我是否搞砸了构造函数、缩放,this.height 是否不正确?我似乎无法弄清楚。

public class Game extends Canvas implements Runnable{

private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;

private Thread thread;
private JFrame frame;
private boolean running = false;

private Screen screen;

private BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();

public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);

screen = new Screen(width, height);
frame = new JFrame();

}

public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}

public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void run() {
while (running) {
update();
render();
}
}

public void update() {

}

public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}

screen.render();
for (int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}

Graphics g = bs.getDrawGraphics();
g.setColor(new Color(0,0,0));
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}


public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("My First Game");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);

game.start();

}
}


public class Screen {

private int width, height;
public int[] pixels;

public Screen(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width * height];
}

public void render() {
for (int y = 0; y < height; y++ ) {
for (int x = 0; x < height; x++ ) {
pixels[x + y * width] =(0xFF00FF);
}
}

}
}

最佳答案

为了使整个屏幕呈现粉红色,您需要进行 2 项调整:

1) 在第 5 行计算高度时更改操作数的顺序,以便先乘后除,如下所示:

public static int height = width * 9 / 16;

原因:表达式是从左到右计算的。由于所有运算符都是整数,因此每个子表达式的结果都会向下舍入。查看差异:

300 / 16 * 9 = 18 * 9 = 162

对比

300 * 9 / 16 = 2700 / 16 = 168

2) render 方法中有一个拼写错误,两次使用了 height 而不是 width。因此渲染出一个矩形。您需要将内部 for 循环中的 height 变量更改为 width

public void render() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) { // use width here instead of height
pixels[x + y * width] = (0xFF00FF);
}
}
}

关于Java 屏幕渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com