我正在构建一个SpriteKit游戏,我正在从多维数组中加载一个级别。 loadlevel函数第一次工作。如果我在println
分配之上physicsBody
进行physicsBody
(在physicBody初始化之后),则会失败。当我使用removeChildrenInArray
删除所有图块时,我第二次运行加载级别时会抛出错误fatal error: unexpectedly found nil while unwrapping an Optional
并且它指向下方println
下方的行。而println
表示physicsBody
是nil
。在我看来,没有理由重新初始化PhysicsBody
应该是nil
。 println
打印physicsBody nil
。我不知道为什么physicsBody
会nil
。我只是试图通过删除所有块节点并根据级别图在原始位置添加新节点来重置级别。
func loadLevel() {
var levels = Levels().data
var frameSize = view.frame.size
var thisLevel = levels[currentLevel]
println("running load level")
for (rowIndex,row) in enumerate(thisLevel) {
for (colIndex,col) in enumerate(row) {
if col == 4 {
continue
}
println("COL: \(col)")
var tile = SKSpriteNode(texture: SKTexture(imageNamed: "brick_\(tileMap[col])"))
tile.name = "tile_\(rowIndex)_\(colIndex)"
tile.position.y = frameSize.height - (tile.size.height * CGFloat(rowIndex)) - (tile.size.height/2)
tile.position.x = tile.size.width * CGFloat(colIndex) + (tile.size.width/2)
var physicsBody = SKPhysicsBody(rectangleOfSize: tile.size)
tile.physicsBody = physicsBody
tile.physicsBody.affectedByGravity = false
tile.physicsBody.categoryBitMask = ColliderType.Block.toRaw()
tile.physicsBody.contactTestBitMask = ColliderType.Ball.toRaw()
tile.physicsBody.collisionBitMask = ColliderType.Ball.toRaw()
scene.addChild(tile)
tileCount++
}
}
}
这是我的ColliderType
enum ColliderType:UInt32 {
case Paddle = 1
case Block = 2
case Wall = 3
case Ball = 4
}
这是我的重置功能内容:
func reset() {
tileCount = 0
var removeTiles = [SKSpriteNode]()
// remove all the tiles
for child in scene.children {
var a_tile = child as SKSpriteNode
if a_tile.name.hasPrefix("tile_") {
a_tile.removeFromParent()
a_tile.name = ""
removeTiles.append(a_tile)
}
}
removeTiles.removeAll(keepCapacity: false)
ball!.position = CGPoint(x: 200, y: 200)
ballVel = CGPoint(x: 0, y: -5)
currentLevel++
loadLevel()
lost = false
won = false
}
这是我的Level
结构
struct Tile {
let map = ["blue","green","purple","red"]
}
struct Levels {
let data = [
[
[4,4,0,4,0,4,0,4,0,4,0,4,0,0,4,4],
[4,4,1,4,1,4,1,4,1,4,1,4,1,1,4,4],
[4,4,2,4,2,4,2,4,2,4,2,4,2,2,4,4],
[4,4,3,4,3,4,3,4,3,4,3,4,3,3,4,4]
],
[
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,4,2,2,2,2,2,2,2,2],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
]
]
}
如果这是Swift中的一个错误,我试图找到解决方法,这样我就可以完成这项工作。
答案 0 :(得分:1)
看起来SKPhysicsBody
实例化为空大小。尝试使用显式大小创建物理主体对象,如下所示:
var physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(100, 100))
或者,您可以直接在SKSpriteNode
上设置大小,或者使用其构造函数之一,这些构造函数采用CGSize构造,如initWithTexture:color:size: