Drawing Moving Tilemap

No.

Create your tiles once, and re-use them. That was the whole point of my post.

//If you find yourself typing out the same number more
//than one time, it's better to make a constant for it.
public static inline var TILE_WIDTH:Int = 90;
public static inline var TILE_HEIGHT:Int = 30;
public static inline var TILES_ACROSS:Int = 9;
public static inline var TILES_DOWN:Int = 20;

public function render() {
    //Create the tiles on the very first frame, and never
    //call "new BGTile()" again.
    if(bgTiles.length == 0) {
        tf.text = "First frame";
        
        for(column in 0...(TILES_ACROSS + 1)) {
            for(row in 0...(TILES_DOWN + 1)) {
                var bgTile:BGTile = new BGTile();
                bgTiles.push(bgTile);
                tilemap.addTile(bgTile);
            }
        }
    } else {
        tf.text = "Not the first frame";
        
        if(playerPosition.equals(lastRenderedPosition)) {
            return;
        }
    }
    
    //Same formula, but consolidated. You can skip startRow and
    //startColumn because they canceled out anyway.
    var roughColumn:Float = playerPosition.x - Math.floor(playerPosition.x / TILE_WIDTH) * TILE_WIDTH;
    var roughRow:Float = playerPosition.y - Math.floor(playerPosition.y / TILE_HEIGHT) * TILE_HEIGHT;
    
    //Place the tiles and set their id.
    var i:Int = 0;
    for(column in 0...(TILES_ACROSS + 1)) {
        for(row in 0...(TILES_DOWN + 1)) {
            var bgTile:BGTile = bgTiles[i];
            i++;
            
            bgTile.x = column * TILES_ACROSS - roughColumn;
            bgTile.y = row * TILES_DOWN - roughRow;
            bgTile.id = mapArray[column][row] - 1;
        }
    }
    
    //Did you mean "lastRenderedPosition = playerPosition.clone()"?
    lastRenderedPosition = playerPosition;
}


//Delete clearArray() unless you used it somewhere else.

class BGTile extends Tile {
    public function new() {
        super();
    }
}
1 Like