现在我正在从char
的2D数组加载我的地图,当我加载超过100个块(10x10区域)时,游戏真的很慢。我让它只在角色的一定距离内渲染块。我也相信我知道为什么它运行如此缓慢,但我不知道如何解决它。下面是代码:
public void renderBlocks(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics 2D)g;
for(int x = 0; x < 50; x++) {
for(int y = 0; y < 50; y++) {
//blocks[x][y] tells it which type of block to load
Block next = new Block(blocks[x][y], x, y);
if((next.getX() - player.getX()) >= (-13*32) &&
(next.getX() - player.getX()) <= (13*32)) {
if((next.getY() - player.getY()) >= (-6*32) &&
(next.getY() - player.getY()) <= (6*32)) {
g2d.drawImage(next.getImage(), (next.getX() - player.getX()),
(next.getY() - player.getY()), this);
}
}
}
}
}
该行:
Block next = new Block(blocks[x][y], x, y);
是什么让它运行得很慢。即使它没有将它们绘制到屏幕上,它仍然为Block next
的所有元素设置new Block(blocks[x][y], x, y)
等于blocks[x][y]
。问题是我不能只删除这行代码,因为它决定了从字符到绘制块的距离。我需要设置它,以便它只设置下一个等于被绘制到屏幕的块[x] [y]的元素。
我尝试过:
if((x - player.getX()) >= (-13*32) && (x - player.getX()) <= (13*32)){
Block next = new Block(blocks[x][y], x, y);
...Rest of Code here
}
围绕它,y - playerY
也一样,但它不起作用,但理论上应该如此。
如果你知道一种方法可以回答这个问题并使游戏运行速度与我从ArrayList加载块时的运行速度一样快,这样我就可以加载超过5000个块并且运行在一个好的FPS上率。如果你需要游戏的源代码来帮助我解决这个问题,请评论你需要它,我会发布它。
答案 0 :(得分:1)
你可以只在玩家周围的牌上做出循环:
super.paint(g);
Graphics2D g2d = (Graphics 2D)g;
// find the block with the player (might need correction)
int playerX = (int) (player.getX() / 32);
int playerY = (int) (player.getY() / 32);
int viewDist = 6;
int lowerX = Math.max(playerX - viewDist, 0);
int upperX = Math.min(playerX + viewDist + 1, 50);
int lowerY = Math.max(playerY - viewDist, 0);
int upperY = Math.min(playerY + viewDist + 1, 50);
for (int x = lowerX; x < upperX; x++)
{
for (int y = lowerY; y < upperY; y++)
{
Block next = new Block(blocks[x][y], x, y);
g2d.drawImage(next.getImage(), (next.getX() - player.getX()),
(next.getY() - player.getY()), this);
}
}