user9693427
user9693427

Reputation:

Swift SpriteKit, Can't fire bullet more than once

I'm making a little game where there is a spaceship and you can fire a bullet, when I run the program and click to fire a bullet, it works, however when I click again it doesn't fire. It gives me

Thread 1: signal SIGABRT

when I try to fire a second time. Could someone please help me?

Here's the code:

import SpriteKit
import GameplayKit
import UIKit

class GameScene: SKScene {

let player = SKSpriteNode(imageNamed: "mySpaceship")
//let stars = SKSpriteNode(imageNamed: "stars")
let bullet = SKSpriteNode(imageNamed: "bullet")

override func didMove(to view: SKView) {
    //print(frame.size.width)
    //print(frame.size.height)

    /*stars.position = CGPoint(x: self.size.width/2, y:self.size.height/2)
    addChild(stars)*/
    player.position = CGPoint(x:0, y:0)
    player.zPosition = 2
    self.addChild(player)


}

func fireBullet() {
    bullet.position = player.position
    bullet.zPosition = 1
    self.addChild(bullet)

    let moveBullet = SKAction.moveTo(y: self.size.height + bullet.size.height, duration: 1)
    let deleteBullet = SKAction.removeFromParent()
    let bulletSequence = SKAction.sequence([moveBullet, deleteBullet])
    bullet.run(bulletSequence)


}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("Fired bullet")
    fireBullet()
}

override func update(_ currentTime: TimeInterval) {
}


}

All of this code is in my GameScene.swift file. Thanks!

UPDATE: After looking at the node counter, I observed that if I fired a bullet after the previous bullet got deleted (making the total node count 2), the bullet would shoot fine. However if I shoot the bullet before the previous bullet has been deleted (which makes the node count 2) the program would crash. Is there anyway to shoot another bullet without waiting for the previous bullet to be deleted?

Upvotes: 0

Views: 226

Answers (1)

Imrul Kayes
Imrul Kayes

Reputation: 648

You just need to initialize your Bullet sprite in fireBullet method.

func fireBullet() {
    // make sure you initialize bullet here.
    let bullet = SKSpriteNode(imageNamed: "bullet")
    bullet.position = player.position
    bullet.zPosition = 1
    self.addChild(bullet)

    let moveBullet = SKAction.moveTo(y: self.size.height +   bullet.size.height, duration: 1)
    let deleteBullet = SKAction.removeFromParent()
    let bulletSequence = SKAction.sequence([moveBullet, deleteBullet])
    bullet.run(bulletSequence)
  }

Upvotes: 1

Related Questions