Search code examples
iosswiftsprite-kitgame-physics

Spritekit - How to create a hole like billiard's pockets?


I am creating a game where a ball is moving on the screen and I would like to create a hole where the ball can go inside (as it happens in billiard)

Can that be a simple circle SKNode with a black background? In this case I should hide the ball when it will go over the hole (which is a really bad effect)

Any other features available / ideas? Thank you


Solution

  • What I would do in this circumstance is create a SKSpriteNode for the hole, with just a black image as the circle. Then when the two nodes collide, you delete the ball node. I'm assuming you are doing this in your GameScene by the way

    First, create an enum for your collision detector:

     enum ColliderType:UInt32 {
        case ball = 1
        case blackhole = 2
    }
    

    Creating a Basic Black Hole Node

    let blackHole:SKNode = SKSpriteNode(imageNamed: "NameOfImage")
        blackHole.physicsBody = SKPhysicsBody(circleOfRadius: side.size.width/2)
        blackHole.physicsBody!.dynamic = false
        //These 3 lines of code basically say to pay attention to collisions
        blackHole.physicsBody!.categoryBitMask = ColliderType.blackhole.rawValue
        blackHole.physicsBody!.contactTestBitMask = ColliderType.ball.rawValue
        blackHole.physicsBody!.collisionBitMask = ColliderType.ball.rawValue
        self.addChild(side)
    

    Also, where you set the physics properties of your balls, insert this code

    (Name of Sprite).physicsBody!.categoryBitMask = ColliderType.ball.rawValue
    (Name of Sprite).physicsBody!.contactTestBitMask = ColliderType.blackhole.rawValue
    (Name of Sprite).physicsBody!.collisionBitMask = ColliderType.blackhole.rawValue
    

    Then, this is where you detect collisions.

    func didBeginContact(contact: SKPhysicsContact)
    {
        //variable stores the two things contacting
        let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
    
        switch(contactMask){
    
        case ColliderType.ball.rawValue | ColliderType.blackhole.rawValue:
            //deletes the ball as a Node
            contact.bodyB.node?.removeFromParent()
    
    
        default:
            return
    
    
    
        }
    }
    

    Let me know if any of it is confusing or if I need to explain more