JGrn84
JGrn84

Reputation: 750

How to add score to SpriteKit using SKAction

runAction(SKAction.repeatActionForever(
   SKAction.sequence([
    SKAction.runBlock(addScore),
      SKAction.waitForDuration(1.0) ]) ))        

func addScore() {
        let scoreSprite = SKSpriteNode(imageNamed: "scoreSprite")

        let actualY = random1(min: scoreSprite.size.height/2, max: size.height - scoreSprite.size.height/2)

        scoreSprite.position = CGPoint(x: size.width + scoreSprite.size.width/2, y: actualY)

        self.addChild(scoreSprite)

        let actualDuration = random1(min: CGFloat(0.5), max: CGFloat(0.5))
        let actionMove = SKAction.moveTo(CGPoint(x: -scoreSprite.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))

        let actionMoveDone = SKAction.removeFromParent()
            scoreSprite.runAction(SKAction.sequence([actionMove, actionMoveDone])) }

Okay, so I want my score to increase by 1 for every second the person plays the game. I looked into using NSTimeInterval but from what I could gather, the better option is to use SKAction. The only way I could think of was to use an almost clear sprite and to move it across the screen every second. What I want to know is how to make a score increase each time the node moves across the screen, or if this is no good what a better option would be. The code I am using to move the node is above. Thanks in advance.

Upvotes: 0

Views: 131

Answers (2)

0x141E
0x141E

Reputation: 12753

Try adding this to your didMoveToView method

let wait = SKAction.waitForDuration(1.0)
let incrementScore = SKAction.runBlock ({
    ++self.score
    self.scoreLabel.text = "\(self.score)"
})

self.runAction(SKAction.repeatActionForever(SKAction.sequence([wait,incrementScore])))

Upvotes: 1

JGrn84
JGrn84

Reputation: 750

I fixed it using by adding this to the end of the scoreSprite function:

    if scoreSprite.position.x > endOfScreenLeft {
        updateScore()
    }

Then did this to update the score:

func updateScore() {
        score++
        scoreLabel.text = String(score)
    }

End of screen left is a CGFloat:

endOfScreenLeft = (self.size.width / 2) * CGFloat(-1)

Upvotes: 0

Related Questions