首先,我定义了一个名为AlienNode
的类,该类继承自SKSpriteNode
,这是该类
var hP = 0
init() {
self.hp = 5
var alienTexture = SKTexture(imageNamed: "Alien_Normal.png")
super.init(texture: alienTexture, color: UIColor.white, size: alienTexture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
在GameScene
中,我在功能didBegin()
let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]
print(nodesName)
if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
//A bullet hit a alien
run(SKAction.playSoundFileNamed("Scream.wav", waitForCompletion: false))
var alienNode: AlienNode
if let _ = contact.bodyA.node as? AlienNode {
contact.bodyB.node?.removeFromParent() //Remove the bullet
alienNode = contact.bodyA.node as! AlienNode
}
else {
contact.bodyA.node?.removeFromParent() //Remove the bullet
alienNode = contact.bodyB.node as! AlienNode
}
alienNode.hP -= 1
print("hit")
if alienNode.hP <= 0 {
alienNode.removeFromParent()
print("Alien killed")
}
结果是,有时会检测到一个碰撞,有时会检测到两次,这让我感到困惑,我该如何解决?