Reputation: 521
I am a fairly new programmer, attempting to make it so that during a bricked breaker like game, when the ball hits the paddle, I would like to add one point to the score. I think I am partway there, but cannot figure it out.
let BallCategory : UInt32 = 0x1 << 0 //
let BottomCategory : UInt32 = 0x1 << 1 //
let BlockCategory : UInt32 = 0x1 << 2 //
let PaddleCategory : UInt32 = 0x1 << 3 //
bottom.physicsBody?.categoryBitMask = BottomCategory
bottom.physicsBody?.contactTestBitMask = BallCategory
paddle.physicsBody?.categoryBitMask = PaddleCategory
paddle.physicsBody?.contactTestBitMask = BallCategory
paddle.physicsBody?.collisionBitMask = BallCategory
ball.physicsBody?.categoryBitMask = BallCategory
ball.physicsBody?.contactTestBitMask = BottomCategory | PaddleCategory
ball.physicsBody?.contactTestBitMask = PaddleCategory
var score = 0
func didBeginContact(contact: SKPhysicsContact) {
score = +1
}
let label = SKLabelNode(fontNamed: "Chalkduster")
label.text = String(score)
label.fontSize = 50
label.fontColor = SKColor.whiteColor()
label.position = CGPoint (x: 568, y: 600)
addChild(label)
These are three sections of my code I believe I need to change in order to have the score work in my game and if you could help me, I would appreciate it.
Upvotes: 2
Views: 783
Reputation: 24572
You have to test if the colliding bodies have the correct bitmasks
before increasing the score
inside didBeginContact
. You can use the following code to increase score
on collision between paddle and ball.
func addScore() {
score += 1
scoreLabel.text = "\(score)"
}
func didBeginContact(contact: SKPhysicsContact) {
var body1 : SKPhysicsBody!
var body2 : SKPhysicsBody!
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
body1 = contact.bodyA
body2 = contact.bodyB
}
else {
body1 = contact.bodyB
body2 = contact.bodyA
}
if body1.categoryBitMask == BallCategory && body2.categoryBitMask == PaddleCategory {
addScore()
}
}
Upvotes: 1