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

不打扰是莪最后的温柔 提交于 2019-11-30 15:57:30

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!