First I defined a class named AlienNode
which inherit from SKSpriteNode
, here's the class
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")
}
in GameScene
, I shoot a bullet to the alien, and detect its collision, in the function 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")
}
the result is, sometimes it detect one collision, sometimes two, which make me confused, how could I fix that?