1
\$\begingroup\$

I'm having some issues with my optimization of my game.

I have a simple tile map looped like this in my case the images are 64 by 64 pixels:

 for (i=0; i < 50; i++){ //horizontal   
    for (j=0; j < 50; j++){ // vertical

    var x = (i-j)*(img[0].height/2) + (canvas.width/2)-(img[0].width/2); 
    var y = (i+j)*(img[0].height/4);

    abposx = x + offset_x;
    abposy = y + offset_y;

    total_load++;       

    ctx.drawImage(img[0],abposx,abposy);        
        }
    }

This as you can see is a 50 by 50 map. But i firstly want to do the following optimizations: Work out the max that fits in canvas window (including partial) so it fills the screen.

The problem i have though by imposing the limit the loops will only load that many tiles ( lets say 10 by 10 ) so the map is always 10 by 10 and as i scroll the rest of tiles remain unloaded for obvious reasons.

So i also need to work out how to change the starting position... any ideas =/ ?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

A few needed variables:

var ac = 5; //active column
var ar = 5; //active row
var tr = 0; //top row
var rc = 0; //left column
var br = 10;//bottom row
var rc = 10;//right column

Now build the row/column when entered Note: this is assuming the coordinates for the tile are in the top-left corner.

if(player.x > tile.width*(ac+1)) { 
    for(i=0; i<img.length; i++) {
        //draw img[rc+1][i]; 
        ac++;
    }
}
if(player.x < tile.width*ac) {
    for(i=0; i<img.length; i++) {
        //draw img[lc-1][i];
        ac--; 
    }
}
if(player.y < tile.height*ar) {
    for(i=0; i<img[tr].length; i++) {
        //draw img[tr][i];
        ar--; 
    }
}
if(player.y > tile.height*(ar+1)) {
    for(i=0; i<img[br-1].length; i++) {
        //draw img[br-1][i];
        ar--; 
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ what is player.x and player.y ? \$\endgroup\$
    – Dave
    Mar 10, 2012 at 6:25
  • \$\begingroup\$ Well, I don't exactly know how you have the scrolling set up, so I assumed it was based on the player's coordinates. You will probably have to tweak the code quite a bit to get it to work with what you are trying to accomplish. Hopefully, this should give you at least an idea. \$\endgroup\$
    – tyjkenn
    Mar 10, 2012 at 7:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .