dannybess
dannybess

Reputation: 599

How To Remove a SKSpriteNode in didBeginContact

How do I remove a SKSpriteNode in the didBeginContact method? I have the node as a global variable, (node:SKSpriteNode!), and I change it's position throughout in a couple functions. However, when it is in contact with another object, I want to remove it from the screen. How should I accomplish that?

 func didBeginContact(contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {
    case ColliderType.Star.rawValue | ColliderType.Cup.rawValue:
        println("")
    default:
        return

Upvotes: 0

Views: 3748

Answers (2)

rakeshbs
rakeshbs

Reputation: 24572

I don't understand why you are using a global variable when you have multiple balls on screen.

if the categoryBitMask of ball is bitMaskBall, you can remove from parent the node that is in the contact object passed to didBeginContact

func didBeginContact(contact: SKPhysicsContact) {

    var ball : SKNode? = nil
    // Change it to categoryBitMask of the ball sprite
    if contact.bodyA.categoryBitMask == bitMaskBall &&  contact.bodyB.categoryBitMask == bottomBitMask { 
        ball = contact.bodyA.node
    }
    else if contact.bodyB.categoryBitMask == bitMaskBall && contact.bodyA.categoryBitMask == bottomBitMask {
        ball = contact.bodyB.node
    }

    ball?.removeFromParent()

}

The conditions check if any of the bodies involved in the contact is the ball using the categoryBitMask of the ball. Then we extract the node inside the colliding body and finally remove it.

Upvotes: 1

Christian
Christian

Reputation: 22343

Just remove it from its parent by using removeFromParent() method:

sprite.removeFromParent()

Upvotes: 0

Related Questions