我正在用Java制作游戏,是rpg,但是,只有在地图上,游戏速度很慢。
该地图是在TiledMap编辑器中制作的,因此可以读取XML并将其加载到ArrayList中。我的电脑是双核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();
}
}
难道我做错了什么?
注意:我是该论坛的新手,更糟糕的是,我不太懂英语,所以请原谅任何错误。
最佳答案
首先,您不应在每次调用期间为图块创建子图像。严格来说,您根本不应该为要绘制的图像调用getSubimage
:它将使图像“不受管理”,这会使渲染性能降低一个数量级。您只应为不想渲染的图像调用getSubimage
-例如,当您最初为图块创建单个图像时。
您显然已经有一个TileSet
类。您可以向此类添加一些功能,以便您可以直接访问图块的图像。
您当前的代码如下:
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(int tile)
方法可以获取已在内部存储的图块。我将从脑海中绘制几行代码,您可能可以将其转移到您的
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);
}
}