The problem is this function:
func begin(_ contact: SKPhysicsContact) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
if nodeA.name == "box" {
boxandballCollision(box: nodeA, ball: nodeB)
} else if nodeB.name == "box" {
boxandballCollision(box: nodeB, ball: nodeA)
}
}
It never gets called. You are probably thinking it should be called just like didBegin(_:)
is, but that function is part of the SKPhysicsContactDelegate
protocol and gets called by the system. The system has no way of knowing to call your new begin(_:)
function.
You need to put your logic into didBegin(_:)
and get rid of your begin(_:)
function. You don't really need a separate function if one of the objects involved in the collision is a box.
Here, for instance, is the relevant code from my Project 11:
func didBegin(_ contact: SKPhysicsContact) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
if nodeA.name == "ball" {
collisionBetween(ball: nodeA, object: nodeB)
} else if contact.bodyB.node?.name == "ball" {
collisionBetween(ball: nodeB, object: nodeA)
}
}
func collisionBetween(ball: SKNode, object: SKNode) {
if object.name == "good" {
score += 1
ballCount += 1
destroy(ball: ball)
} else if object.name == "bad" {
score -= 1
destroy(ball: ball)
} else if object.name == "box" {
//we have an obstacle object
object.removeFromParent()
}
}
See how we already know that one of the objects involved is a ball, so all we really need to do in collisionBetween(ball:object:)
is check what the other object is.