0
\$\begingroup\$

I am making a small game where I store information about the world around the player (like tiles) using a small 2d array of integers. In the game you can scroll the screen to the left or right. I also want to be able to read portions of the world from a file instead of loading the entire world at once for performance reasons. My concept of doing this is when the camera has scrolled a certain amount, shift the array by a certain amount and replace the old array data with new information from the file. I'm not sure if this makes sense performance wise or if there is a more performance friendly way of doing this so I was wondering if anybody could provide some insight. I drew an image to show what I am talking about.enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ You can avoid the copying/moving using a "Clipmap" strategy, where you just overwrite the column that has scrolled off screen with the column that has scrolled on screen, and the rest of the data stays where it is. What moves is your access window for looking up into the array — you van use modular arithmetic so that it wraps around the physical array to still read the tiles as though they were laid out the way you expect to see them on screen. I show a little of this technique in this answer (you can ignore the hashing parts). \$\endgroup\$
    – DMGregory
    Jun 18 '21 at 10:29
0
\$\begingroup\$

That looks like how I'd do it. If possible, use an array or array-like data structure that lets you add and remove elements.

Pseudo-code:

//O(1) or O(n) depending on data structure
public void ScrollRight(var newColumn) {
    //remove leftmost column. this will shift other columns left one
    columns.RemoveAt(0);
    //insert new column in the rightmost position
    columns.Add(newColumn);
}
//O(1) or O(n) depending on data structure
public void ScrollLeft(var newColumn) {
    //remove rightmost column.
    columns.RemoveAt(columns.Count - 1);
    //insert new column in the leftmost position, shifting other columns right one
    columns.Insert(newColumn, 0);
}

The above is much more efficient than this approach:

//DON'T do it this way if you can avoid it
//O(n x m), where n = # of columns and m = # of rows
public void ScrollRight(var newColumn) {
    //shift each column left by copying its data to the previous column
    for (int c = 0; c < columns.Count - 1; c++) {
        var column = columns[c];
        var nextColumn = columns[c + 1]
        for (int r = 0; r < column.Count; r++) {
            column[r] = nextColumn[r];
        }
    }
    //copy new data into the last column, replacing old data
    var lastColumn = columns[columns.Count - 1];
    for (int r = 0; r < column.Count; r++) {
        lastColumn[r] = newColumn[r];
    }
}
\$\endgroup\$

You must log in to answer this question.

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