我正在关注SpriteKit的教程,它有一个IF语句的问题.该线的逻辑如下:如果子弹和小行星发生碰撞,则将其移除.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// remove bullet and asteroid
}
Run Code Online (Sandbox Code Playgroud)
当试图确保小行星(body2.node)在可关闭区域之前可以关闭之前,会出现问题.为此,作者添加了以下内容:
body2.node?.position.y < self.size.height
Run Code Online (Sandbox Code Playgroud)
制作完整的IF声明如下:
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node?.position.y < self.size.height {
// remove bullet and asteroid
}
Run Code Online (Sandbox Code Playgroud)
显然这条线与Swift 2配合使用,但是Swift 3进行了一次校正,从一个可选的位置改变了位置,并且力量展开了位置.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node!.position.y < self.size.height {
// remove bullet and asteroid
}
Run Code Online (Sandbox Code Playgroud)
通过强行展开位置,当三个物体碰撞时,应用程序崩溃了"我认为".在看屏幕时真的很难分辨.
我正在测试下面的代码,我还没有遇到任何问题.你们认为下面的修复工作会起作用吗?我在想的是,如果我确定body2.node不是nil,那么没有理由为什么应用程序应该崩溃,因为在尝试强行打开它时不会遇到nil.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if body2.node != nil {
if ( body2.node!.position.y < self.size.height ) {
// remove bullet and asteroid
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果有其他方式,你们可以建议一种不同的方式来编写原始的IF声明?
谢谢
是的,该if != nil声明(目前正在编写)将防止强制解包引起的崩溃.
另一种方法是使用if letSwift中的语法:
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if let body2Node = body2.node {
if body2Node.position.y < self.size.height {
// remove bullet and asteroid
}
}
}
Run Code Online (Sandbox Code Playgroud)
好处是它会!从您的代码中删除它,并且更清楚地将nil检查与您稍后使用的变量连接起来.