在Swift中以编程方式创建SKTileMapNode

在Swift中以编程方式创建SKTileMapNode

问题描述:

请问有人知道如何使用Swift以编程方式创建SKTileMapNode吗? (注意:我不想使用编辑器执行此操作,我只想以编程方式实现该功能)

does anyone know how to create an SKTileMapNode programmatically using Swift please? (NOTE: I do not want to do this using the editor, I want to achieve this programmatically only)

我已经尝试了以下操作,但未渲染我的图块

I have tried the following but does not render my tile map

let bgTexture = SKTexture(imageNamed: "background")
let bgDefinition = SKTileDefinition(texture: bgTexture, size: bgTexture.size())
let bgGroup = SKTileGroup(tileDefinition: bgDefinition)
let tileSet = SKTileSet(tileGroups: [bgGroup])
let bgNode = SKTileMapNode(tileSet: tileSet, columns: 5, rows: 5, tileSize: bgTexture.size())
bgNode.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
bgNode.setScale(1)
self.addChild(bgNode)

任何帮助表示赞赏

要使用单个背景图块布局整个地图,您将迭代每一列和每一行.您需要先获取背景图块.

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)

还有SKTilemapNode的初始化程序,该初始化程序接受SKTileGroup

There is also an initialiser for SKTilemapNode that accepts SKTileGroup

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

我强烈建议利用Xcode内置的功能来创建TileSet和TileMap.您仍然可以以编程方式填写地图.

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