首先创建一个扩展WorldView
类的新类。我打电话给我的新班级Background
。因此,在这个新类中导入所有需要的Java包,以覆盖paintBackground
方法。这应该是:
import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;
接下来在类名后确保它说延伸WorldView
。事情是这样的:
public class Background extends WorldView
然后声明Game
类型的变量游戏类型的图像可变Image
是这样的:
private Game game;
private Image image;
然后在这个类的构造函数确保类型的游戏Game
位于构造函数的签名中,在调用super
时,您将不得不初始化WorldView
,初始化游戏并初始化图像变量,如下所示:
super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();
然后,您只需重写paintBackground
方法,方法与覆盖Player
类中的paint
方法时的方法完全相同。就像这样:
public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}
现在终于必须声明一个类级别的参考刚才在Game
类所做的新的类,并在Game
构造函数初始化这一点,是这样的:
private Background image;
And in the Game constructor:
image = new Background(this);
最后,你所要做的就是将背景添加到框架中!这是我确信我们都错过了的事情。要做到这一点,你有自己的变量frame
已被宣布后,做这样的事情:
frame.add(image);
确保你只frame.pack();
之前添加此代码。 另外请确保您使用的背景图像不是太大!
现在就是这样!我注意到游戏引擎可以处理JPEG和PNG图像格式,但也可以支持其他图像格式。尽管这有助于在游戏中包含背景图像,但它并不完美!因为一旦你进入下一个关卡,所有你的平台和精灵都是看不见的,你可以看到的是你的背景图像和你包含在游戏中的任何JLabels/Jbuttons。
谢谢你的回答。我有一些问题 - 1.有关图像应放在哪里?你可以给我一个图像的源代码路径,因为我不确定它应该如何布局。 – Dew 2009-02-08 00:55:01
2.说如果我使用上面的代码创建一个名为'Background'的类,我需要在我的'Game'类(控制视图,游戏窗口的大小)中调用从Background类到使背景图像出现?请举个例子。 – Dew 2009-02-08 00:58:47
这里是我目前使用的代码来设置我的游戏窗口的背景颜色 - view = new WorldView(world,width,height); view.setBackground(new Color(230,245,255)); – Dew 2009-02-08 00:59:28