Programmatically create SKTileMapNode in Swift

人走茶凉 提交于 2019-11-30 21:58:32

To layout the entire map with the single background tile you would iterate through each column and each row. You'll need to retrieve the background tile first.

let tile = bgNode.tileSet.tileGroups.first(
    where: {$0.name == "background"})

for column in 0..4 {
    for row in 0..4 {
        bgNode.setTileGroup(tile, forColumn: column, row: row)
    }
}

There is also a convenience function to achieve a flood fill;

bgNode.fill(with: tile)

There is also an initialiser for SKTilemapNode that accepts SKTileGroup

let bgNode = SKTileMapNode(tileSet: tileSet, columns: 5, rows: 5, tileSize: bgTexture.size(), fillWithTileGroup: tile)

I strongly recommend to leverage the functionality built into Xcode for creating TileSets and TileMaps. You can still programatically fill the map.

In case it's helpful to anyone, here's the whole thing put together:

class MyGameScene: SKScene {
    override func didMove(to view: SKView) {
        guard let tileSet = SKTileSet(named: "testset") else {
            // hint: don't use the filename for named, use the tileset inside
            fatalError()
        }

        let tileSize = tileSet.defaultTileSize // from image size
        let tileMap = SKTileMapNode(tileSet: tileSet, columns: 5, rows: 5, tileSize: tileSize)
        let tileGroup = tileSet.tileGroups.first
        tileMap.fill(with: tileGroup) // fill or set by column/row
        //tileMap.setTileGroup(tileGroup, forColumn: 5, row: 5)
        self.addChild(tileMap)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!