ARKit&SceneKit入门

SpriteKit(11) - 瓦片地图

2017-08-03  本文已影响136人  li_礼光

瓦片地图

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)
    }
}
瓦片地图
上一篇 下一篇

猜你喜欢

热点阅读