How to use SKScene's didBegin to detect when Sprite Node hits enclosure?
I have 100% success when using contactTestBitMask to detect contact between 2 sibling Sprite Nodes .. but cannot solve when a Sprite Node contacts its enclosure:
this works!
myBall = SKSpriteNode(imageNamed: ballImg)
myBall.name = "ball"
myBall.physicsBody?.categoryBitMask = ballCategory
myBall.physicsBody?.collisionBitMask = noCollision
myBall.physicsBody?.contactTestBitMask = playerCategory // Ball hit by Player
NOT so much =
myRoom = SKSpriteNode(imageNamed: roomImg)
myRoom.name = "room"
myRoom.physicsBody?.categoryBitMask = roomCategory
myRoom.physicsBody?.collisionBitMask = noCollision
myRoom.physicsBody?.contactTestBitMask = ballCategory // Room wall hit by Ball
Here's my SKScene's didBegin() code:
func didBegin(_ contact: SKPhysicsContact) {
let bodyAName = contact.bodyA.node?.name // e.g., = player
let bodyBName = contact.bodyB.node?.name // e.g., = ball
let playerHitsBall = ((bodyBName == myPlayer.name) && (bodyAName == myBall.name)) ||
((bodyAName == myPlayer.name) && (bodyBName == myBall.name))
let ballHitsWall = ((bodyBName == myBall.name) && (bodyAName == myRoom.name)) ||
((bodyAName == myBall.name) && (bodyBName == myRoom.name))
if playerHitsBall {
print("works!")
itsGameViewController.moveBall(dx: dBallX, dy: dBallX)
}
if ballHitsWall {
print("does NOT show")
itsGameViewController.moveBallIfBallHitsWall()
}
}
Please note I can generate code to test for contacting the frame of the enclosure outside didBegin - but that adds a ton of overhead.
My real goal is to do it within didBegin if possible.
Based on history, I am probably doing something, although basic, is wrong ... but I can't seem to find it.
Thanks in advance.