-1

我似乎无法弄清楚它在谈论哪个可选值或为什么我会收到此错误。我检查了我的分数整数,并确保我声明它的值为 0,直到它与敌人接触。在模拟器中,计数器会计算前 4 或 5 个敌人,然后崩溃。

var score = Int? ()
var scoreLabel = UILabel ()
override func didMoveToView(view: SKView) {

scoreLabel.text = "\(score)"
scoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 
20))
scoreLabel.textColor = UIColor.blackColor()

score = nil
if score == nil {
    score = 0
    scoreLabel.text = "\(score!)"
}
func didBeginContact(contact: SKPhysicsContact) {

let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB

if ((firstBody.categoryBitMask == PhysicsCategory.bullet) &&  
(secondBody.categoryBitMask == PhysicsCategory.enemy) ||
(firstBody.categoryBitMask == PhysicsCategory.enemy) && 
(secondBody.categoryBitMask == PhysicsCategory.bullet)) {
 //i get the error next line            
collisionWithBullet((firstBody.node as! SKSpriteNode), 
bullet: (secondBody.node as! SKSpriteNode))
 }
}

func collisionWithBullet(enemy: SKSpriteNode, bullet: SKSpriteNode){

score? += 1
scoreLabel.text = "\(score!)"
enemy.removeFromParent ()
bullet.removeFromParent ()

}
4

1 回答 1

1

将分数更改为

var score = 0

代替

var score = Int? ()

而不是这部分

score = nil
if score == nil {
    score = 0
    scoreLabel.text = "\(score!)"
}

只写这个

scoreLabel.text = "\(score)"

编辑:而不是这部分

collisionWithBullet((firstBody.node as! SKSpriteNode), 
bullet: (secondBody.node as! SKSpriteNode))

做这样的事情

if let firstNode = firstBody.node as? SKSpriteNode,
 secondNode = secondBody .node as? SKSpriteNode {
collisionWithBullet((firstNode), 
    bullet: (secondNode))
}
于 2016-04-13T06:05:14.813 回答