swiftsprite-kitskphysicsbody

Determine only one contact SpriteKit


The main question is: How to determine only one contact?

part of code:

extension GameScene : SKPhysicsContactDelegate {


func didBegin(_ contact: SKPhysicsContact) {
    let bodyA = contact.bodyA.categoryBitMask
    let bodyB = contact.bodyB.categoryBitMask
    let ball = BitmaskCategory.ball
    let bucket = BitmaskCategory.bucket



    if bodyA == ball && bodyB == bucket || bodyA == bucket && bodyB == ball {
        print("contact")
//            block.run(SKAction.repeatForever(blockInstanse.rotateBlock(block: block)))

    }
}} 

When I put ball in bucket, i have that output because ball has bouncing effect. Want to write some logic in that func but I can't because have several contacts. Tried to change ball.physicsBody?.categoryBitMask in "if" condition but without success too. Please help...


Solution

  • Your ball or bucket can set a flag on the first contact, you can check inside the didBegin and run action if is true, like:

    var isFirstContact = true
    
    func didBegin(_ contact: SKPhysicsContact) {
        let bodyA = contact.bodyA.categoryBitMask
        let bodyB = contact.bodyB.categoryBitMask
        let ball = BitmaskCategory.ball
        let bucket = BitmaskCategory.bucket
    
    
    
        if bodyA == ball && bodyB == bucket || bodyA == bucket && bodyB == ball {
            if isFirstContact {
                isFirstContact = false
                // block.run(SKAction.repeatForever(blockInstanse.rotateBlock(block: block)))
            }
        }
    }}