2个SKSpriteNodes发生碰撞时更新标签

时间:2016-11-21 22:04:06

标签: sprite-kit swift3

每当球与主要球碰撞时,我想向topLbl添加1点。我该怎么办?谢谢!

import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {
    var ball = SKSpriteNode()
    var main = SKSpriteNode()
    var topLbl = SKLabelNode()
    var score = [Int]()

    override func didMove(to view: SKView) {
        startGame()
        self.physicsWorld.contactDelegate = self
        topLbl = self.childNode(withName: "topLabel") as! SKLabelNode
        ball = self.childNode(withName: "ball") as! SKSpriteNode
        main = self.childNode(withName: "main") as! SKSpriteNode
        ball.physicsBody?.applyImpulse(CGVector(dx: 8, dy: 8))
        let border = SKPhysicsBody(edgeLoopFrom: self.frame)
        border.friction = 0
        border.restitution = 1
        self.physicsBody = border
    }

    func startGame() {
        score = [0]
        topLbl.text = "\(score[0])"
    }

    func addScore(byTouch : SKSpriteNode){
        if byTouch == main {
            score[0] += 1
        }
        print(score)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)

            main.run(SKAction.moveTo(x: location.x, duration: 0))
            main.run(SKAction.moveTo(y: location.y, duration: 0))
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        main.run(SKAction.moveBy(x: 4444, y: 4444, duration: 0))
    }


    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }

    func didBegin(contact: SKPhysicsContact) {
        if (contact.bodyA.categoryBitMask == 1 && contact.bodyB.categoryBitMask == 2) {
            if ball == contact.bodyA.node as! SKSpriteNode  {
                    score[0] += 1
            }
        } else if (contact.bodyA.categoryBitMask == 2 && contact.bodyB.categoryBitMask == 1) {
            if ball == contact.bodyB.node as! SKSpriteNode {
                score[0] += 1
            }
        }
    }
}

0 个答案:

没有答案