当我运行此代码时,第一个CollisionWithplayer行给出了错误的指令错误。错误并不是每次都出现,只是偶尔出现一次,没有相似的条件来确定导致错误的原因。
func didBeginContact(contact: SKPhysicsContact) {
let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB
if ((firstBody.categoryBitMask == PhysicsCategory.Goblin) && (secondBody.categoryBitMask == PhysicsCategory.Bullet) ||
(firstBody.categoryBitMask == PhysicsCategory.Bullet) && (secondBody.categoryBitMask == PhysicsCategory.Goblin))
{
CollisionWithBullet(firstBody.node as! SKSpriteNode, Bullet: secondBody.node as! SKSpriteNode)
}
else if ((firstBody.categoryBitMask == PhysicsCategory.Goblin) && (secondBody.categoryBitMask == PhysicsCategory.player) ||
(firstBody.categoryBitMask == PhysicsCategory.player) && (secondBody.categoryBitMask == PhysicsCategory.Goblin)){
CollisionWithplayer(firstBody.node as! SKSpriteNode, player: secondBody.node as! SKSpriteNode)
}
func CollisionWithBullet(Goblin: SKSpriteNode, Bullet:SKSpriteNode){
Goblin.removeFromParent()
Bullet.removeFromParent()
score += 1
ScoreLbl.text = "\(score)"
var explosion = SKEmitterNode(fileNamed: "Goblin Death Animation.sks")
explosion!.particlePosition = Goblin.position
self.addChild(explosion!)
var fire = SKEmitterNode(fileNamed: "Goblin Death Animation 2.sks")
fire!.particlePosition = Goblin.position
self.addChild(fire!)
}
func CollisionWithplayer(Goblin: SKSpriteNode, player: SKSpriteNode){
let ScoreDefault = NSUserDefaults.standardUserDefaults()
ScoreDefault.setValue(score, forKey: "Score")
ScoreDefault.synchronize()
if (score > Highscore){
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setValue(score, forKey: "Highscore")
}
Goblin.removeFromParent()
player.removeFromParent()
self.view?.presentScene(EndScene())
ScoreLbl.removeFromSuperview()
}
答案 0 :(得分:1)
我假设您收到错误,因为您的代码不会处理1次碰撞导致didBeginContact方法多次触发的情况(碰撞发生在同一节点的2个点)
我会像这样重写你的代码以避免这种情况(使用选项)。此外,我稍微重写了一下,因此您不必为每次碰撞编写2个if语句。
phoneFault = raw_input("Is your phone physically damaged?")
while phoneFault != "Yes" and phoneFault != "No":
print("Error; you can only answer 'Yes' or 'No' to the questions.")
if phoneFault == "Yes" or phoneFault == "yes":
phoneFault = raw_input("Is your phone wet?")
if phoneFault == "Yes" or phoneFault == "yes":
phoneFault = raw_input("Are you able to turn it off?")
if phoneFault == "Yes" or phoneFault == "yes":
print("Send the phone to the manufacturer and ask if they can fix it.")
elif phoneFault == "No" or phoneFault == "no":
print("Dry the phone, and then wait for the phone to run out of power and then restart it.")
请同时遵循swift guidlines,你的方法和属性应该开始,小写字母不会是大写字母。
希望这有帮助