gpt4 book ai didi

swift - 意外发现 Nil SKSpriteNode

转载 作者:行者123 更新时间:2023-11-28 06:45:18 26 4
gpt4 key购买 nike

当子弹与飞机接触时出现以下错误。

fatal error: unexpectedly found nil while unwrapping an Optional value

Screenshot of error

平面函数:

func addPlane() {
var myplane : SKSpriteNode?
myplane = SKSpriteNode(imageNamed: "plane")
let actualY = random(min: 100, max: size.height - myplane!.size.height/2)
myplane!.position = CGPoint(x: size.width + myplane!.size.width/2, y: actualY)
myplane!.physicsBody = SKPhysicsBody(rectangleOfSize: myplane!.size) // 1
myplane!.physicsBody?.dynamic = false // 2
myplane!.physicsBody!.categoryBitMask = CollisionCategoryPowerUpOrbs
myplane!.physicsBody!.collisionBitMask = 0
myplane!.name = "plan"
addChild(myplane!)//
let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0))
let actionMove = SKAction.moveTo(CGPoint(x: -myplane!.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
myplane!.runAction(SKAction.sequence([actionMove]))

}

当用户触摸屏幕时,它会用这个函数发射子弹:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchLocation = touch.locationInNode(self)
var projectile : SKSpriteNode?
projectile = SKSpriteNode(imageNamed: "bomb")
projectile!.position = CGPoint(x: 50, y: 100.0)
projectile!.physicsBody = SKPhysicsBody(circleOfRadius: projectile!.size.width/2)
projectile!.physicsBody?.dynamic = true
projectile!.physicsBody!.allowsRotation = false
projectile!.physicsBody!.categoryBitMask = CollisionCategoryPlayer
projectile!.physicsBody!.contactTestBitMask = CollisionCategoryPowerUpOrbs
projectile!.physicsBody!.collisionBitMask = 0
projectile!.physicsBody!.linearDamping = 1.0
projectile!.name = "shot"
let offset = touchLocation - projectile!.position
if (offset.x < 0) { return }
addChild(projectile!)
let direction = offset.normalized()
let shootAmount = direction * 1000
let realDest = shootAmount + projectile!.position
let actionMove = SKAction.moveTo(realDest, duration: 2.0)
let actionMoveDone = SKAction.removeFromParent()
projectile!.runAction(SKAction.sequence([actionMove, actionMoveDone]))
}

在接触时隐藏平面的函数:

func didBeginContact(contact: SKPhysicsContact) {
let nodeB = contact.bodyA.node!
if nodeB.name == "plan" {
nodeB.removeFromParent()
}
}

我在 ViewDidLoad 中调用 addPlane 函数,如下所示:

runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addPlane),
SKAction.waitForDuration(1.5)
])
))

最佳答案

用'?'改变你的代码做一个零检查:

func didBeginContact(contact: SKPhysicsContact) {

let nodeB = contact.bodyA.node
if nodeB?.name == "plan" {
nodeB?.removeFromParent()
}
}

此解决方案将防止崩溃,但缺点是仍会触发一些不必要的接触事件。

应避免删除 didBeginContact 中的节点。这可能会导致节点已被移除(无),但 PhysicsBody 仍处于事件状态的情况。(另请参阅 KnightOfDragon 的评论)

关于swift - 意外发现 Nil SKSpriteNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com