Alessandro Nardinelli
Alessandro Nardinelli

Reputation: 237

Removing sprite from scene when contact is made

So in my game i want to really make the life index more dynamic and not just an label that counts down. I've add three sprites on top of the screen like this:

Life sprite

They are inserted by this code in a for loop:

// Add Life to player

    var lifeIndexCount = 0
    var positionAdd:CGFloat = 10.0

    for lifeIndexCount in 0..<3 {

        let lifeIndex = SKSpriteNode(imageNamed: "bullet.png")

        lifeIndex.position = CGPoint(x: self.frame.size.width * -1.5, y: self.frame.size.height * 0.93)

        let lifeIndexMove = SKAction.moveTo(CGPoint(x: (size.width * 0.05) + positionAdd, y: size.height * 0.93), duration: NSTimeInterval(0.7))

        let lifeIndexRotation = SKAction.rotateByAngle(CGFloat(-2 * M_PI), duration: 0.3)

        lifeIndex.runAction(SKAction.sequence([lifeIndexMove, lifeIndexRotation]))

        addChild(lifeIndex)

        positionAdd = positionAdd + 25.0

I want to remove each one as soon as the player ship misses a shot. Like a little animation of the life sprite rotating and get of the screen. I've set my contact delegate but i don't know how to grab them and animate so they can go off when a miss shot occurred.

func didBeginContact(contact: SKPhysicsContact) {

    var contactBody1: SKPhysicsBody
    var contactBody2: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {

        contactBody1 = contact.bodyA
        contactBody2 = contact.bodyB

    } else {

        contactBody1 = contact.bodyB
        contactBody2 = contact.bodyA

    }

    if ((contactBody1.categoryBitMask == 1) && (contactBody2.categoryBitMask == 2)) {

        //Run when the bullet contacts the line

        contactBody2.node!.removeFromParent()

        // I WANT TO INSERT CODE HERE TO REMOVE A LIFE AT THE TOP


    } else if ((contactBody1.categoryBitMask == 2) && (contactBody2.categoryBitMask == 4)) {

        //Run when the bullet contacts the limbo

    }

}

Thanks!

Upvotes: 1

Views: 243

Answers (1)

user396030
user396030

Reputation: 263

There are several ways to do it, but they all pretty much boil down to giving the node you want animated and removed a name, and matching that name in didBeginContact:. I'm fond of enumerateChildNodesWithName for readability and ease of use. The baked in pattern matching is pretty handy if your use case has something like arrowSprite1, arrowSprite2, etc...

It's also a good idea to clean up anything else that node may be doing, like cancelling SKActions or requests sent out to selectors.

https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/index.html#//apple_ref/occ/instm/SKNode/enumerateChildNodesWithName:usingBlock:

Upvotes: 1

Related Questions