SKPhysicsContact is there a way to determine which body is A and B?

in SpriteKit, we find the didBeginContact method. but it looks a little silly to do something like this: func didBeginContact (contact: SKPhysicsContact) {

    if let contactA = contact.bodyA.node?.name {

        if let contactB = contact.bodyB.node?.name {

            //now that we have safely unwrapped these nodes, we can operate on them

            if contactA == "ball" {

                collisionBetweenBall(contact.bodyA.node!, object: contact.bodyB.node!)

            } else if contactB == "ball" {

                collisionBetweenBall(contact.bodyB.node!, object: contact.bodyA.node!)

            }

        }

    }

}

Is there a way to ensure that bodyA is always a ball? are there any rules related to the category of bitmask?

+4
source share
2 answers

If you use simple categories, with each physical body belonging to only one category, then this alternative didBeginContact form may be more readable:

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

switch contactMask {

   case categoryBitMask.ball | categoryBitMask.something:
       print("Collision between ball and something")
       let ballNode = contact.bodyA.categoryBitMask == categoryBitMask.ball ? contact.bodyA.node! : contact.bodyB.node!
       ballNode.pop()
       score += 10

   default :
       //Some other contact has occurred
       print("Some other contact")
   }
}

, , , AND (categoryBitMask.ball | categoryBitMask.something) .

+5

-, .

enum PhysicsCategory {
     static let ball: UInt32 =  0x1 << 0
     static let wall: UInt32 =  0x1 << 1
     static let enemy: UInt32 = 0x1 << 2
}

 ball.physicsBody?.categoryBitMask = PhysicsCategory.ball
 ball.physicsBody?.contactTestBitMask = PhysicsCategory.wall | PhysicsCategory.enemy

 wall.physicsBody?.categoryBitMask = PhysicsCategory.wall
 wall.physicsBody?.contactTestBitMask = 0 

 enemy.physicsBody?.categoryBitMask = PhysicsCategory.enemy
 enemy.physicsBody?.contactTestBitMask = 0 

. , , . , 1 , 0 , .

, , double if.

func didBegin(_ contact: SKPhysicsContact) {

    let firstBody: SKPhysicsBody
    let secondBody: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }


    // Ball hit wall or wall hit ball
    if (firstBody.categoryBitMask == PhysicsCategory.ball) && (secondBody.categoryBitMask == PhysicsCategory.wall) {

          // Some code
    }

    // Ball hit enemy or enemy hit ball
    if (firstBody.categoryBitMask == PhysicsCategory.ball) && (secondBody.categoryBitMask == PhysicsCategory.enemy) {

          // Some code
    }
}

didMoveToView , .

physicsWorld.contactDelegate = self

,

0

Source: https://habr.com/ru/post/1659909/


All Articles