What is the proper way to programmatically create a SpriteKit SKTileMap?

前端 未结 1 865
孤城傲影
孤城傲影 2021-01-01 00:49

I am creating a tile map for an iOS game I am working on. The map is a top down view of an island. Most of the tiles are water, but some are land. The water tile is reuse

相关标签:
1条回答
  • 2021-01-01 01:49

    One approach is to define the map layout in a text file with columns and rows that specify which tile to place at specific locations. Then it will be possible to specify a different map for each game level, while still using the same scene. This example assumes there is only one SKTileSet and flood filling the background is not required.

    // Level1.txt
    01 01 01 01 01 01 63 64
    01 01 01 01 53 54 55 56
    01 01 43 44 45 46 47 48
    01 34 35 36 37 01 39 40
    25 26 27 01 01 30 31 01
    17 18 01 20 21 22 23 01
    01 01 11 12 13 01 01 01
    01 01 03 01 01 01 01 01
    

    Iterate over each column and row, retrieve the specified tile and call setTileGroup.

    let path = Bundle.main.path(forResource: "Level1.txt", ofType: nil)
    do {
        let fileContents = try String(contentsOfFile:path!, encoding: String.Encoding.utf8)
        let lines = fileContents.components(separatedBy: "\n")
    
        for row in 0..<lines.count {
            let items = lines[row].components(separatedBy: " ")
    
            for column in 0..<items.count {
                let tile = tileMap.tileSet.tileGroups.first(where: {$0.name == "map-tile-" + items[column]})
                tileMap.setTileGroup(tile, forColumn: column, row: row)
            }
        }
    } catch {
        print("Error loading map")
    }
    

    This eliminates the second block of code in your example. If you want to compromise a bit on using Xcode GUI Tools, then the first block of code could be eliminated by creating the SKTileGroup as an sks file.

    I would recommend using the GUI Tools when working with SKTileMapNode though, since they provide a lot of functionality.

    0 讨论(0)
提交回复
热议问题