gpt4 book ai didi

java - Java 游戏中不显示背景图像

转载 作者:行者123 更新时间:2023-12-02 05:30:07 24 4
gpt4 key购买 nike

这是我之前的一个问题的后续问题。我正在制作一个java游戏,它基本上是一个带有角色图像的JFrame,一些由fillRect()组成的健康栏,它们都位于背景图像的顶部。问题是生命条和角色出现了,但背景图像没有出现。

这是 Game 类的简化版本,其中包含 main() 和 render() 方法:

public class Game extends Canvas implements Runnable{

public static boolean running = false;
public Thread gameThread;

private BufferedImage playerSpriteSheet;
private ImageManager im;

private static Player player;
private static HealthBar healthBars;
private static BackgroundImage backgroundImage;

public void init(){
ImageLoader loader = new ImageLoader();
playerSpriteSheet = loader.load("/spriteSheet.png");
SpriteSheet pss = new SpriteSheet(playerSpriteSheet);

im = new ImageManager(pss);

backgroundImage = new BackgroundImage("/background.png");
player = new Player(800, 250, im);
healthBars = new HealthBar(200, 200);

this.addKeyListener(new KeyManager());
}

public synchronized void start() {
if(running)return;
running = true;
gameThread = new Thread(this);
gameThread.start();
}

public synchronized void stop() {
if(!running)return;
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60D;
double ns = 1_000_000_000/amountOfTicks;
double delta = 0;
long now = System.nanoTime();

while(running)
{
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1)
{
tick();
delta--;
}
render();
}
stop();
}

public void tick() {
player.tick();
}

public void render() {

BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3); //Use 5 at most
return;
}
Graphics g = bs.getDrawGraphics();

//RENDER HERE
backgroundImage.render(g);
player.render(g);
healthBars.render(g);


//END RENDER
g.dispose();
bs.show();
}

public static void main(String[] args)
{
JLabel backgroundImage;
JLabel controlKeyPanel;
JLabel statusLabel;

Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

JFrame frame = new JFrame("Title");
frame.setResizable(false);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setLayout(new BorderLayout());

backgroundImage = new JLabel(new ImageIcon("/background.png"));

String htmlButtonGuide = "words";
controlKeyPanel = new JLabel(htmlButtonGuide);

statusLabel = new JLabel("label");


frame.add(backgroundImage, BorderLayout.CENTER);
frame.add(controlKeyPanel, BorderLayout.EAST);
frame.add(statusLabel, BorderLayout.SOUTH);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);

frame.setVisible(true);

game.start();
//Program seems to continue running after ESC
}

public static Player getPlayer() {
return player;
}

}

这是 BackGroundImage 类:

public class BackgroundImage {

private Image background = null;


public BackgroundImage(String s) {
if(s == null)
{
background = getImage(s);
}
}

public void render(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(background, 0, 0, 1200, 600, null);
}

public Image getImage(String path) {

Image tempImage = null;

File image2 = new File(path);
try {
tempImage = ImageIO.read(image2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return tempImage;
}
}

我关心 render() 方法重用“g”Graphics 对象将所有 3 个东西添加到屏幕上。有人告诉我不要将轻量级的 Swing 生命值条与厚重的 AWT 背景和角色结合起来?谁能指出我正确的方向来显示背景?渲染方法是否应该不考虑背景?我只需要把背景放一次。它不需要像生命条和角色那样不断更新,对吗?

最佳答案

让我们从...开始

backgroundImage = new BackgroundImage("/background.png");

这变成了...

File image2 = new File(path);

File image2 = new File("/background.png");

所以你可以看到它...你能看出这个有问题吗?这是请求一个位于当前驱动器根位置的文件...这并不是我认为您想要的...

The images are stored in a folder called "res" in the main project folder

这表明您想要使用...

backgroundImage = new BackgroundImage("res/background.png");

假设图像不是嵌入资源......

下一步...

public BackgroundImage(String s) {
if (s == null) {
background = getImage(s);
}
}

因此,您只想在引用为 null 时尝试加载图像???

旁注...

frame.setSize(WIDTH * SCALE, HEIGHT * SCALE); 是一个坏主意,因为框架的边框占据了框架本身内部的空间。

最好重写 CanvasgetPreferredSize 方法并提供您要使用的默认大小值,然后在框架上调用 pack 。这将计算框架的大小作为其内容的首选大小加上框架边框要求...

你的“游戏循环”正在疯狂运行......

while (running) {
delta += (now - lastTime) / ns;
lastTime = now;
if (delta >= 1) {
tick();
delta--;
}
render();
}

基本上,这将尽可能快地运行,并将减少其他线程运行的机会,最终使您的游戏(可能还有您的电脑)崩溃

这是运行循环的“简单”概念......

public void run() {
init();
final long amountOfTicks = 60;
long ns = Math.round(1_000_000_000 / (double)amountOfTicks);

int frames = 0;
long frameStart = System.currentTimeMillis();

while (running) {
long startedAt = System.nanoTime();
tick();
render();
long completedAt = System.nanoTime();
long duration = completedAt - startedAt;

long frameEnd = System.currentTimeMillis();
if (frameEnd - frameStart >= 1000) {
System.out.println(frames);
frames = 0;
frameStart = System.currentTimeMillis();
} else {
frames++;
}

long rest = ns - duration;
if (rest > 0) {
rest = TimeUnit.MILLISECONDS.convert(rest, TimeUnit.NANOSECONDS);
try {
Thread.sleep(rest);
} catch (InterruptedException ex) {
}
}
}
stop();
}

基本上,它会尝试确保每次迭代之间有足够的延迟,以维持您试图达到的 60fps 目标...而不会让系统挨饿...

关于java - Java 游戏中不显示背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25636507/

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