Gaurav Manchanda
Gaurav Manchanda

Reputation: 19

Need Assistance, Swift 2.0 SKSpriteNode

Im quite new to swift programming language, recently I started following a Youtube Tutorial to create a space shooter game. One thing I was curious about however (not mentioned in tutorial) is how do I add a limit to the number of bullets.

import SpriteKit

//Declaring Player
let player = SKSpriteNode(imageNamed: "playerShip")

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        //Declaring Background
        let background = SKSpriteNode(imageNamed: "background")

        //Setting Properties For Background
        background.size = self.size
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.zPosition = 0
        self.addChild(background)


        //Setting Properties For Player (Already Declared)
        player.setScale(1.3)
        player.position = CGPoint(x: self.size.width/2, y: self.size.height * 0.20)
        player.zPosition = 2
        self.addChild(player)

    }

    func fireBullet(){

        //Setting Properties & Declaring Bullet
        let bullet = SKSpriteNode(imageNamed: "bullet")
        bullet.setScale(1)

        bullet.position = player.position
        bullet.zPosition = 1
        self.addChild(bullet)

        //Moving and Deleting Bullet
        let moveBullet = SKAction.moveToY(self.size.height + bullet.size.height, duration: 1)
        let deleteBullet = SKAction.removeFromParent()
        let bulletSequence = SKAction.sequence([moveBullet,deleteBullet])
        bullet.runAction(bulletSequence)


    }

    //This function will run when screen is touched
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        fireBullet()

    }

}

Upvotes: 1

Views: 65

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59536

If you want to limit the total number of bullets the player can shot, then you can create a property of GameScene representing the number of remaining bullets

class GameScene: SKScene {
    private var remainingBullets = 10
    ...

Next, when fireBullet() is invoked you need to check if there are remaining bullets available. If so then the fireBullet() execution can continue otherwise you return.

Last thing you need to decrease remainingBullets.

func fireBullet(){
    guard remainingBullets > 0 else {
        print("No more bullets")
        return
        }
    /// .... Do shooting stuff in here ...
   //... 
    remainingBullets -= 1
 }

Upvotes: 2

Related Questions