瓦片地图
import SpriteKit
class TileMap : SKScene {
override func didMove(to view: SKView) {
self.size = UIScreen.main.bounds.size
self.addChild(createTileMap())
}
func createTileMap() -> TileMapNode {
return TileMapNode(altesName: "scenery",
tileSize: CGSize(width: UIScreen.main.bounds.size.width/15,
height: UIScreen.main.bounds.size.height/15),
tileCodes: [
"xxxxxxxxxxxxxxx",
"x-------------x",
"x-------------x",
"x-------------x",
"x-------------x",
"x----xxxxxx---x",
"x----x--------x",
"x----x--------x",
"x----xxxxx----x",
"x--------x----x",
"x--------x----x",
"x-------xx----x",
"x-------xx----x",
"x-------xx----x",
"xxxxxxxxxxxxxxx",
])
}
}
class TileMapNode : SKNode {
var tileSize : CGSize = CGSize() //保存瓷砖大小
var altes : SKTextureAtlas?//添加纹理集
init(tileSize : CGSize) {
super.init()
self.tileSize = tileSize
}
//初始化
convenience init(altesName : String, tileSize : CGSize, tileCodes : [String]) {
self.init(tileSize: tileSize)
altes = SKTextureAtlas(named: altesName)
for row in 0..<tileCodes.count {
let line = tileCodes[row]
for (col,code) in line.enumerated() {
if let tile = nodeForCode(tileCode: code) {
tile.position = postionForRow(row: row, col: col)
self.addChild(tile)
}
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func nodeForCode(tileCode : Character) -> SKNode?{
if altes == nil {
return nil
}
var tile : SKNode?
switch tileCode {
case "x":tile = SKSpriteNode(texture: SKTexture(imageNamed: "wall"))
case "o":tile = SKSpriteNode(texture: SKTexture(imageNamed: "grass"))
default:print("unkown tile code \(tileCode)")
}
if let sprite = tile as? SKSpriteNode {
sprite.blendMode = .replace
}
return tile
}
func postionForRow(row : Int , col: Int) -> CGPoint {
let x = CGFloat(col) * tileSize.width + tileSize.width/2
let y = CGFloat(row) * tileSize.height + tileSize.height/2
return CGPoint(x: x, y: y)
}
}
瓦片地图
-
这里的地图和设计的倒置了,这个就不纠结位置了.
-
地图的设置其实也是根据对应的布局添加固定的节点.
-
这里是是一种是设计的思路,添加节点和前面的的知识样.
-
这里还可以通过加载Txt文件,TML文件到地图中
网友评论