Search code examples
iossprite-kitswift4xcode92d-games

SpriteKit | Double hit Explosion Bug


I am currently working on the finishing touches of my Space Shooter. In this shooter you hit asteroids and when hit the an explosion animation is played. How ever later in the game when it gets faster and 2 asteroids show up on the screen at the same time and IF they explode at the same time the first explosion function will not complete leaving the last image shown before the second explosion on screen. This eventually piles up until there are so many nodes on the screen that the game crashes, despite the fact that it looks shitty.

My current code for the Explosion Function is:

func spawnEpxlotion(spawnPosition: CGPoint){

    let explosion1 = SKTexture(imageNamed: "explosion-1")
    let explosion2 = SKTexture(imageNamed: "explosion-2")
    let explosion3 = SKTexture(imageNamed: "explosion-3")
    let explosion4 = SKTexture(imageNamed: "explosion-4")
    let explosion5 = SKTexture(imageNamed: "explosion-5")
    let explosion6 = SKTexture(imageNamed: "explosion-6")
    let explosion7 = SKTexture(imageNamed: "explosion-7")
    let explosion8 = SKTexture(imageNamed: "explosion-8")
    let explosion9 = SKTexture(imageNamed: "explosion-9")

    let animateExplosion = SKAction.sequence([
        SKAction.wait(forDuration: 0, withRange: 0),
        SKAction.animate(with: [explosion1,explosion2,explosion3,explosion4,explosion5,explosion6,explosion7,explosion8,explosion9], timePerFrame: 0.03)])

    explosion = SKSpriteNode(texture: explosion1)
    explosion.position = spawnPosition
    explosion.setScale(2)
    self.addChild(explosion)
    explosion.run(explosionSound)
    explosion.run(animateExplosion, completion : {self.explosion.removeFromParent()})
}

It all works like a charm until a double hit occurs. I tried a few possible fixes, but none of them did it. Most of them just turned off the explosion function all together, which is obviously not the goal.

If someone could help me with that that would be cool. Maybe there is a way to force complete a function regardless if it is called twice at the same time.


Solution

  • Your explosion variable is not declared in your function, which suggests that it must be an instance variable. When you call spawnEpxlotion while the previous animation is still running, and you get to the line explosion = SKSpriteNode(texture: explosion1), you're blowing away the node that was running the animation. Make explosion a local variable. Best of luck to you.