Jollyvideos
Jollyvideos

Reputation: 103

Insert counter enemies killed

I'm developing a simple 2D play and would like to implement a counter for every enemy killed and keep it displayed on the display until the game is over.

How would I do this? I'm using Xcode 7.3.1

My Enemies code is :

func frecciaInCollisioneConNemico(freccia:SKSpriteNode, nemico:SKSpriteNode) {
    print("Freccia ha colpito un nemico")
    freccia.removeFromParent()
    nemico.removeFromParent()

    nemiciDistrutti += 1
    print("hai distrutto \(nemiciDistrutti) nemici")

    if (nemiciDistrutti >= 20) {
        let rivela = SKTransition.flipHorizontalWithDuration(0.5)
        let gameOverScene = GameOverScene(size: self.size, vinto: true)
        self.view?.presentScene(gameOverScene, transition: rivela)
    }
}

Upvotes: 0

Views: 84

Answers (1)

crashoverride777
crashoverride777

Reputation: 10674

You should be able to answer this question by yourself as it is very easy.

Create your label

class GameScene: SKScene {

    let enemiesKilledLabel = SKLabelNode(fontNamed: "HelveticaNeue")

    override func didMoveToView(view: SKView) {
        loadEnemiesKilledLabel()  
    }

    private func loadEnemiesKilledLabel() {
        enemiesKilledLabel.position = ...
        enemiesKilledLabel.text = "0"
        ...
        addChild(enemiesKilledLabel)
    }
}

Than in your death function you just update the text.

 ...
 nemiciDistrutti += 1

 enemiesKilledLabel.text = "\(nemiciDistrutti)" // update text

This is called string interpolation, you can read more about it here

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

As a tip you should change your collision method to take in optionals. There could be a case where 1 collision calls multiple contacts because multiple body parts collided. Your code is not taking this into account and therefore you could crash if frecciaInCollisioneConNemico is called multiple times in fast succession.

Change it to this

func frecciaInCollisioneConNemico(freccia: SKSpriteNode?, nemico: SKSpriteNode?) {

    guard let freccia = freccia, nemico = nemico else { return }

    freccia.removeFromParent()
    nemico.removeFromParent()
    ...
}

Lastly I would recommend you try to write your code in english only.

Hope this helps

Upvotes: 1

Related Questions