当我触摸对象时,如何运行Score Label?

时间:2016-02-21 16:58:33

标签: xcode swift sprite-kit sprite

我在游戏中添加了Score Label。但它并没有运行。当我触球时,分数应该增加。我无法将球与得分标签联系起来。谁能帮我?这是我的代码:

 override func didMoveToView(view: SKView) {
      super.didMoveToView(view)



    let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)


    borderBody.friction = 0

    self.physicsBody = borderBody



    physicsWorld.gravity = CGVectorMake(5, 5)

    let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode
    ball.physicsBody!.applyImpulse(CGVectorMake(10, -10))

    scoreLabel.fontName = "Helvetica Neue Light"
    scoreLabel.text = "Score: 0"
    scoreLabel.fontSize = 40
    scoreLabel.color = SKColor.redColor()
    scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
    scoreLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Top
    scoreLabel.position = CGPoint(x: 250, y: size.height -  100)
    addChild(scoreLabel)



 }

还有触控代码:

   override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch:AnyObject in touches{
        let location = (touch as! UITouch).locationInNode(self)
        let nodeTouched = nodeAtPoint(location)
        let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode


     //Detect if the ball is touched
        if(nodeTouched == ball){

            physicsWorld.gravity = CGVectorMake(-30, 30)
        }

}

1 个答案:

答案 0 :(得分:1)

请改为尝试:

     if ((nodeTouched.name?.containsString(BallCategoryName)) != nil) {

        //Update Score

     }

请记住,我们并不确切知道BallCategoryName是什么或如何设置它,所以你必须确保它不是零。

此外,如果您touchesBegan中的当前方法成功运行了physicsWorld.gravity = CGVectorMake(-30, 30)行,那么我们就会知道您的scoreLabel属性出现问题,而不是触摸检测方法。< / p>

如果是我,我只会将ball作为您场景的属性,然后在touchesBegan中进行测试:

if self.ball.containsPoint(touchLocation) {
    //Update Score
}