Swift Spritekit联系人位掩码和分数标签

时间:2015-03-03 02:53:17

标签: ios swift sprite-kit game-physics bitmask

我是一个相当新的程序员,试图让它成为一个类似于游戏的砖块破坏者,当球击中球拍时,我想在分数上加一点。我想我在那里,但无法理解。

    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)

这些是我的代码的三个部分我相信我需要更改才能让分数在我的游戏中运行,如果你能帮助我,我会很感激。

1 个答案:

答案 0 :(得分:1)

在增加bitmasks score之前,您必须测试碰撞体是否具有正确的didBeginContact。您可以使用以下代码在paddle和ball之间的碰撞中增加score

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()
    }
}