ios – Swift创建一个类来绘制一个tile图并将地图添加到游戏场景中

我创建了一个类,目前我正在尝试创建一个由36个彩色方块组成的瓦片地图,这些方块是SKSpriteNodes.我收到运行时错误,我认为问题是由于SKSpriteNodes没有正确添加到SKNode.我是SpriteKit的新手并试图在
Swift中编写它.

下面是我的地图类(我知道它当前不是Isometric)和我正在尝试使用它的GameScene类.

任何人都可以解释我哪里出错了,对于我是否以特别糟糕的方式做事的任何一般性评论都将不胜感激.

class IsometricMap {

let map = SKNode()
let mapLayout = Array<Array<Int>>()
let numColumns: Int
let numRows: Int
let tileHeight: Int
let tileWidth:Int
let grassNode: SKSpriteNode
let wallNode: SKSpriteNode

init(mapLayout: Array<Array<Int>>,numColumns: Int, numRows: Int, tileHeight: Int, tileWidth: Int) {
    self.mapLayout = mapLayout
    self.numColumns = numColumns
    self.numRows = numRows
    self.tileHeight = tileHeight
    self.tileWidth = tileWidth
    self.grassNode = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(CGFloat(tileHeight), CGFloat(tileWidth)))
    self.wallNode = SKSpriteNode(color: UIColor.brownColor(), size: CGSizeMake(CGFloat(tileHeight), CGFloat(tileWidth)))
}

func drawMap() {
    var tileType: Int
    var columnCount = 0
    var rowCount = 0
    for column in mapLayout {
        for row in column {
            var xPos = columnCount * tileWidth
            var yPos = rowCount * tileHeight
            tileType = mapLayout[columnCount][rowCount]
            placeTile(tileType, xPos: CGFloat(xPos), yPos: CGFloat(yPos))
            ++rowCount
        }
        ++columnCount
    }
}

func placeTile(tileType: Int, xPos: CGFloat, yPos: CGFloat) {
    switch tileType{
    case 0:
        grassNode.position = CGPointMake(xPos, yPos)
        map.addChild(grassNode)
    case 1:
        wallNode.position = CGPointMake(xPos, yPos)
        map.addChild(wallNode)
    default:self
        println("Out of range error")
    }
}

}

class GameScene: SKScene {

let simpleMap = [[1, 1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1]]

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let myLabel = SKLabelNode(fontNamed:"Chalkduster")
    myLabel.text = "Hello, World!";
    myLabel.fontSize = 65;
    myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));

    let starterMap = IsometricMap(mapLayout: simpleMap, numColumns: 6, numRows: 6, tileHeight: 50, tileWidth: 50)
    starterMap.drawMap()
    self.addChild(starterMap.map)

    //self.addChild(myLabel)
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
}

}

最佳答案 据我所知,您不断更改grassNode和wallNode的位置,然后将其重新添加到地图节点.如果我正确理解您的意图,您希望为每个placeTile重新创建grass或wallnode,并每次添加该(新创建的)节点.

我也会从SKNode继承IsometricMap,我认为不需要额外的map变量.
期望类的用户调用drawMap以使类处于一致状态也感觉很奇怪,但是没有足够的上下文来建议什么是最好的替代方案(我的第一个想法是将该功能放在init方法中)

点赞