0

I'm using Graphics2D to draw a map on my game.

In the loop it calls this:

for(int i = 0; i < tiles.length; i++){
        for(int j = 0; j < tiles[i].length; j++){
            if(tiles[i][j]==1){ //GRASS
                g2d.drawImage(getImage.getTile("grass.png", 0, 0, ), i* 32, j* 32, null);
            }
            if(tiles[i][j]==2){ //ROCK
                g2d.drawImage(getImage.getTile("rock.png", 0, 0), i* 32, j* 32, null);

            }

        }
}

And in the method getImage.getTile("grass.png") its just a separate class I made to return a buffered image of the path given.

Now this all works, but it lags like there's no tomorrow. Like I'll press D to go to the right and it takes 3 seconds then the map shifts over in a very laggy fashion! Please help!

Here is the code for the buffered image:

public static BufferedImage getTile(String name, int x, int y){
    try{
        BufferedImage imageMap;
        imageMap = ImageIO.read(getImage.class.getResource("/tiles/"+name));
        BufferedImage a = imageMap.getSubimage(x * 32, y * 32 , 32, 32);
        return a;
    }catch(Exception e){

    }
    return null;
}

PLEASE NOTE:

Everything DOES work, I'm not here because of errors, just lag!

Frostsoft
  • 46
  • 8

1 Answers1

4

And in the method getImage.getTile("grass.png") its just a seprate class i made to return a buffered image of the path given.

You are reading the file every time you invoke this method. Since this code is executed in a loop you have lots of overhead.

The BufferedImage should only be created once when the class is created.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • So would it be better if i did something like ` BufferedImage grass = ImageIO.read(this.class.getResource("grass.png")); BufferedImage stone = ImageIO.read(this.class.getResource("stone.png")); for(int i = 0; i < tiles.length; i++){ for(int j = 0; j < tiles[i].length; j++){ if(tiles[i][j]==1){ //GRASS g2d.drawImage(grass, i* 32, j* 32, null); } if(tiles[i][j]==2){ //ROCK g2d.drawImage(stone, i* 32, j* 32, null); } } }` Thanks tho! – Frostsoft Jul 01 '13 at 01:37
  • I can't read code posted in a comment. The idea is to create the image once and assign it to a variable. Then your painting code references the variable. The reading of the image should NOT be done in you painting routine, since your painting routine will also be called multiple time. – camickr Jul 01 '13 at 01:50