Hussain Mustafa Hussain Mustafa - 5 months ago 16
Swift Question

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)


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))


Now what should i do.

Answer Source

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.