我似乎无法弄清楚它正在讨论哪个可选值或为什么我收到此错误。我检查了我的分数整数,并确保我宣布它的值为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 ()
}
答案 0 :(得分:2)
将分数设为非可选,并将0设为默认分数
var score = 0
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()
//指定nil得分并检查nil ???
//score = nil
//if score == nil {
// score = 0
// scoreLabel.text = "\(score!)"
//}
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 // score is no more optional. default score is 0
scoreLabel.text = "\(score!)"
enemy.removeFromParent ()
bullet.removeFromParent ()
}