有没有人知道如何使用Swift以编程方式创建SKTileMapNode? (注意:我不想使用编辑器执行此操作,我只想以编程方式实现此目的)
我尝试过以下操作,但不会渲染我的瓷砖地图
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)
任何帮助非常感谢
答案 0 :(得分:5)
要使用单个背景图块布局整个地图,您将遍历每列和每行。您需要先检索背景图块。
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)
}
}
还有便利功能来实现洪水填充;
bgNode.fill(with: tile)
SKTilemapNode
还有一个接受SKTileGroup
let bgNode = SKTileMapNode(tileSet: tileSet, columns: 5, rows: 5, tileSize: bgTexture.size(), fillWithTileGroup: tile)
我强烈建议利用Xcode内置的功能来创建TileSets和TileMaps。您仍然可以以编程方式填充地图。
答案 1 :(得分:3)
如果它对任何人都有帮助,这就是整个事情的组合:
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)
}
}