在 Swift 中以编程方式创建 SKTileMapNode [英] Programmatically create SKTileMapNode in Swift

查看:61
本文介绍了在 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.

这篇关于在 Swift 中以编程方式创建 SKTileMapNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆