我正在尝试学习Java游戏开发,希望有一天能上大学。我目前正在关注教程并学习基础知识。但是,按照教程进行操作后,我的渲染不会完全渲染,它只会渲染预期屏幕的一半。以下代码是我使用的2个类。我是否搞砸了构造函数,缩放比例,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);
}
}
}
}
答案 0 :(得分:1)
要使整个屏幕呈现粉红色,您需要进行2种修改:
1)在计算第5行的高度时,请更改操作数的顺序,以使您首先相乘然后相除,如下所示:
public static int height = width * 9 / 16;
原因:表达式是从左到右求值的。由于所有运算符都是整数,因此每个子表达式的结果均四舍五入。看到不同之处:
300 / 16 * 9 = 18 * 9 = 162
vs
300 * 9 / 16 = 2700 / 16 = 168
2)渲染方法中有一个错字,其中两次使用高度而不是宽度。因此,将渲染一个矩形。您需要将内部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);
}
}
}