Search code examples
swiftobjectsprite-kitmultiple-instancessknode

Adding multiple instances of objects spritekit swift 3


I am trying to add multiple instances of my object (bullet) so the player can shoot the bullet and then shoot another bullet. I am using the following code but it is giving me a thread 1 signal sigbart error. Can someone please explain whats wrong with the code? Thanks!

            let bulletmove = SKAction.moveTo(y: self.frame.height, duration: 2)

            let bulletremove = SKAction.removeFromParent()

            addChild(bullett)

            bullett.run(SKAction.sequence([bulletmove, bulletremove])) 

Solution

  • if you add an SKSprite multiple times it would an error would occur.

    What you need to do is create an SKSpritenode to add each time. You can have a function to do create bullets eachtime

    func addBullet(){
    
    var bullet = SKSpriteNode(imagenamed: "bullet")
    bullet.position = //Give the point of origin as CGPoint. Maybe same as the shooter..
    addChild(bullet)
    bullet.run(SKAction.moveTo(y: self.frame.height, duration: 2))
    
    }
    

    So each time you call addBullet(),maybe in touches began , you can create new bullet that moves to end of screen without a crash. So main point is have var bullet = SKSpriteNode(imagenamed: "bullet") for each addChild.