Reputation: 607
Hi I am trying to refine my logic for collision between two nodes in my game. I want to update the score and hide the node when the player comes in contact with the coins. It works properly but the score is updated many times throughout contact with the hidden node. I want to know if there is a way to just run it once so that the score is update once. here is my code
//MARK: SKPhysicsContactDelegate methods
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory) {
gameOver = 1
movingObjects.speed = 0
presentGameOverView()
}
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
coinSound()
contact.bodyB.node?.hidden = true
score = score + 1
println(score)
}
}
Upvotes: 0
Views: 116
Reputation: 24572
You can check if the node is hidden before increasing score.
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory) {
gameOver = 1
movingObjects.speed = 0
presentGameOverView()
}
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
if !contact.bodyB.node?.hidden // Added line
{
coinSound()
contact.bodyB.node?.hidden = true
score = score + 1
println(score)
}
}
}
To remove it from parent
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory) {
gameOver = 1
movingObjects.speed = 0
presentGameOverView()
}
if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
if contact.bodyB.node?.parent != nil {
coinSound()
contact.bodyB.node?.removeFromParent()
score = score + 1
println(score)
}
}
}
Upvotes: 1