我正在为 Java 中的 2d 平台游戏制作基本大纲......我遇到了一个最近开始的问题!有时,当我运行我的程序时,我的框架出现了,一切都设置好了,你可以看到那个人,但由于某种原因,地面没有被“添加”(我有一个 addGround() 方法,我在运行的第一段)。随着我对游戏的深入了解,这种情况开始越来越多地发生,直到现在,大部分时间它都失败了,不会显示/添加地面!但是,有时它可以完美地完成。
这是它工作时的样子:
这是它在大多数时候的样子,当它不起作用时:
所以,这是我的主要类代码:(我没有包括所有的导入和东西,只是核心)
public BusiWorld()
{
this.setFocusable(true);
if(init)
{
ground.addGround(x-300, y+100, 35, 1);
ground.addGround(x-100, y-360, 1, 46);
ground.addGround(x+100, y+90, 1, 1);
ground.addGround(x+400, y+20, 2, 1);
ground.addGround(x+460, y-50, 2, 1);
ground.addGround(x+520, y-120, 2, 1);
ground.addGround(x+460, y-190, 2, 1);
ground.addGround(x+140, y-260, 15, 1);
ground.addGround(x, y-280, 1, 1);
init = false;
}
t = new Timer(16, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
repaint();
}
});
t.start();
}
public static void main(String[] args)
{
mainFrame.setTitle("Busiworld");
mainFrame.setSize(600,500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBackground(Color.WHITE);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
这是地面类代码:
public class Ground extends JFrame
{
private Image groundImg = Toolkit.getDefaultToolkit().getImage("ground.png");
private ArrayList<Point> groundLocs = new ArrayList<Point>();
public Ground()
{
}
public void addGround(int xCoord, int yCoord, int howManyWide, int howManyTall)
{
for(int i = 0; i < howManyWide; i++)
{
for(int j = 0; j < howManyTall; j++)
{
groundLocs.add(new Point(xCoord+i*groundImg.getWidth(null), yCoord+j*groundImg.getHeight(null)));
}
}
}
public void drawGround(Graphics g)
{
for(Point p: groundLocs)
{
g.drawImage(groundImg, p.x, p.y, this);
}
}
public int groundArraySize()
{
return groundLocs.size();
}
public Point getGroundArray(int index)
{
return groundLocs.get(index);
}
}