Hussain Mustafa
Hussain Mustafa

Reputation: 107

Delete Nodes Spritekit when interact

I have a circle in the center of my view. Circles known as enemyBall come and collide with it. I want to detect these collisions and then remove the enemyBalls from the view.

func generateEnemyBall(){

    let enemyBall = SKSpriteNode()
    let randomColor = Int((arc4random_uniform(UInt32(circleTextures.count))))
    enemyBall.texture = SKTexture(imageNamed: circleTextures[randomColor])
    enemyBall.size = CGSize(width: mainCircle.size.width / 5, height: mainCircle.size.width / 5)
    enemyBall.physicsBody = SKPhysicsBody(circleOfRadius: enemyBall.size.width / 2)
    enemyBall.physicsBody?.affectedByGravity = false

    let quadrant = Int(arc4random_uniform(UInt32(3)))
    enemyBallForce = -CGFloat(arc4random_uniform(UInt32(100)))

    switch quadrant {

    case 0:

        enemyBall.position = CGPoint(x: self.frame.maxX - 20, y: self.frame.maxY - 100)

        self.addChild(enemyBall)

        let dx = (enemyBall.position.x) - mainCircle.position.x
        let dy = (enemyBall.position.y) - mainCircle.position.y

        let impulse = applyImpulse(dx: dx, dy: dy)
        enemyBall.physicsBody?.applyImpulse(CGVector(dx: enemyBallForce * impulse.dx, dy: enemyBallForce * impulse.dy))

        break

Now what should i do.

Upvotes: 1

Views: 110

Answers (3)

Hussain Mustafa
Hussain Mustafa

Reputation: 107

Well after digging through. This is what worked best for me, as i was generating enemyBalls randomly.

func didBegin(_ contact: SKPhysicsContact) {

    contact.bodyB.node?.removeFromParent()

}

Body B as i know was going to be the enemyBall, hence i accessed it's node and then removed it. Simply using removed some of the nodes.

 enemyBall.removeFromParent()

Thankyou @DeepakRastogi and @JPAquino

Upvotes: 0

Deepak Rastogi
Deepak Rastogi

Reputation: 86

I am a bit newer to swift that's why I would like to answer your question using objective C.

In didMoveToView add:

self.physicsWorld.contactDelegate = self;

add few more properties to your enemyball i.e.

enemyball.physicsBody.categoryBitMask = ballhitcategory;
enemyball.physicsBody.collisionBitMask = ballhitcategory;
enemyball.physicsBody.contactTestBitMask = ballhitcategory;

where ballhitcategory could be any unsigned constant integer value.

Then in didBeginContact delegate method:

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *body1,*body2;

    body1 = contact.bodyA;
    body2 = contact.bodyB;

    //Do your ball removal here.
}

Upvotes: 1

JP Aquino
JP Aquino

Reputation: 4066

Declare the SKPhysicsContactDelegate

class GameScene: SKScene, **SKPhysicsContactDelegate** {
...
}

This delegate method gets called when there is contact:

  func didBegin(_ contact: SKPhysicsContact) {
...
}

Delete node

enemyBall.removeFromParent()

Upvotes: 0

Related Questions