我正在用java制作一个游戏,是一个RPG,但是,只有 map 游戏很慢。 该 map 是在 TiledMap Editor 中制作的,因此是读取并加载到 ArrayList 中的 XML。我的电脑是双核 3.0、4GB RAM、1GB 视频。 渲染完成如下:
//method of tileset class
public void loadTileset(){
positions = new int[1 + tilesX * tilesY][2];
int yy = 0;
int xx = 0;
int index = 0;
// save the initial x and y point of each tile in an array named positions
// positions[tileNumber] [0] - X position
// positions[tileNumber] [1] - Y position
for(int i = 1 ; i < positions.length; i++){
if(index == tilesX ){
yy += tileHeight;
xx = 0;
index = 0;
}
positions[i][0] = xx;
positions[i][1] = yy;
xx += tileWidth;
index++;
}
}
//method of map class
public void draw(Graphics2D screen){
//x and y position of each tile on the screen
int x = 0; int y = 0;
for(int j = 0; j < 20 ; j++){
for(int i = initialTile ; i < initialTile + quantTiles ; i++){
int tile = map[j][i];
if(tile != 0){
screen.drawImage(tileSet.getTileImage().getSubimage(tileSet.getTileX(tile), tileSet.getTileY(tile),tileSet.getTileWidth(), tileSet.getTileHeight()),x,y,null);
}
x += tileSet.getTileWidth();
}
x = 0;
y += tileSet.getTileHeight();
}
}
我做错了什么吗? 注意:我是论坛新手,更糟糕的是我不太懂英语,所以请原谅任何错误。
最佳答案
首先,您不应在每次调用期间为图 block 创建子图像。严格来说,对于要绘制的图像,您根本不应该不调用getSubimage
:这将使图像“不受管理”,并且这会降低渲染性能的数量级。您应该只对不想渲染的图像调用 getSubimage
- 例如,当您最初为图 block 创建单独的图像时。
您显然已经有一个 TileSet
类。您可以向此类添加一些功能,以便您可以直接访问图 block 的图像。
您当前的代码如下所示:
screen.drawImage(
tileSet.getTileImage().getSubimage(
tileSet.getTileX(tile),
tileSet.getTileY(tile),
tileSet.getTileWidth(),
tileSet.getTileHeight()),
x,y,null);
您可以将其更改为如下所示:
screen.drawImage(tileSet.getTileImage(tile), x,y,null);
这里建议的getTileImage(inttile)
方法可以获取内部存储的图 block 。
我会随心所欲地画出几行代码,您可能能够将其转移到您的 TileSet
类中:
class TileSet
{
private Map<Integer, BufferedImage> tileImages;
TileSet()
{
....
prepareTileImages();
}
private void prepareTileImages()
{
tileImages = new HashMap<Integer, BufferedImage>();
for (int tile : allPossibleTileValuesThatMayBeInTheMap)
{
// These are the tiles that you originally rendered
// in your "draw"-Method
BufferedImage image =
getTileImage().getSubimage(
getTileX(tile),
getTileY(tile),
getTileWidth(),
getTileHeight());
// Create a new, managed copy of the image,
// and store it in the map
BufferedImage managedImage = convertToARGB(image);
tileImages.put(tile, managedImage);
}
}
private static BufferedImage convertToARGB(BufferedImage image)
{
BufferedImage newImage = new BufferedImage(
image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
// This is the new method: For a given "tile" value
// that you found at map[x][y], this returns the
// appropriate tile:
public BufferedImage getTileImage(int tile)
{
return tileImages.get(tile);
}
}
关于java - java中的慢速 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685311/