Search code examples
swiftsprite-kitgame-physicsskspritenode

Attemped to add a SKNode which already has a parent swift


I am creating a game and i keep getting this error for my bullet spawn method linked with a joystick. I want to repetitively spawn nodes when the joystick is active Here is how i am creating a firing method

override func didMoveToView(view: SKView) {

if fireWeapon == true {

 NSTimer.scheduledTimerWithTimeInterval(0.25, target: self, 
 selector: Selector ("spawnBullet1"), userInfo: nil, repeats: true)
 }
}
func spawnBullet1(){

self.addChild(bullet1)

bullet1.position = CGPoint (x: hero.position.x , y:hero.position.y) 
bullet1.xScale = 0.5
bullet1.yScale = 0.5
bullet1.physicsBody = SKPhysicsBody(rectangleOfSize: bullet1.size)
bullet1.physicsBody?.categoryBitMask = PhysicsCategory.bullet1
bullet1.physicsBody?.contactTestBitMask = PhysicsCategory.enemy1
bullet1.physicsBody?.affectedByGravity = false
bullet1.physicsBody?.dynamic = false
}
override func touchesBegan(touches: Set<UITouch>, withEvent  
event:UIEvent?) {

for touch in touches {
    let location = touch.locationInNode(self)

    let node = nodeAtPoint(location)
    if (CGRectContainsPoint(joystick.frame, location)) {
        stickActive = true

        if stickActive == true {

        fireWeapon = true
}

the first bullet launches as planned and works great however, every time the second bullet launches the app crashes and i get the error. can someone tell me an alternative way to create a fire rate


Solution

  • Instead of self.addChild(bullet1) you need something like self.addChild(SKSpriteNode(imageNamed: "bullet.png"))

    This because you need to create a new bullet every time you fire, you do not want to move the same bullet every single time.