在 Swift 2 中检测物理接触

Detecting Physics Contact in Swift 2

我想在我的应用程序中检测两个对象之间的接触。我有一个 enum 来定义不同的类型:

enum ColliderType: UInt32 {

    case Ball = 0b010
    case Object = 0b001
    case Gap = 0b100

}

我还添加了 SKPhysicsContactDelegate 到我的 SKView:

didMoveToView,我有

self.physicsWorld.contactDelegate = self

这是我定义的对象

ball = SKSpriteNode(texture: ballTexture)
    ball.position = CGPoint(x: CGRectGetMidX(self.frame) - self.frame.width/12, y: self.frame.size.height - (self.frame.size.height - 100))
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ballTexture.size().height)
    ball.physicsBody!.dynamic = false
    ball.physicsBody?.allowsRotation = false
    ball.physicsBody!.categoryBitMask = ColliderType.Ball.rawValue
    ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
    ball.physicsBody!.collisionBitMask = ColliderType.Object.rawValue


let boxTexture = SKTexture(imageNamed: "Obstacle.png")
    let box1 = SKSpriteNode(texture: boxTexture)
    box1.size = CGSizeMake(self.frame.width/4, self.frame.width/8)
    box1.runAction(moveAndRemoveBoxes)
    box1.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
    box1.physicsBody!.dynamic = false
    box1.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
    box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
    box1.physicsBody!.collisionBitMask = ColliderType.Object.rawValue

let gap = SKSpriteNode()
    gap.size = box1.size
    gap.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
    gap.physicsBody!.dynamic = false
    gap.physicsBody!.categoryBitMask = ColliderType.Gap.rawValue
    gap.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
    gap.physicsBody!.collisionBitMask = ColliderType.Gap.rawValue

didBeginContact 函数中我有:

func didBeginContact(contact: SKPhysicsContact) {

    if contact.bodyA.categoryBitMask == ColliderType.Gap.rawValue || contact.bodyB.categoryBitMask == ColliderType.Gap.rawValue {

        print("score")
        score++

        scoreLabel.text = String(score)

    } else {

        if gameOver == false {

            gameOver = true

            self.speed = 0


        }

    }
}

如果你点击屏幕,球对象会从屏幕的一半跳到另一半,名为 box1 的对象在屏幕的一半上 "falling down" 和 "invisible" 间隙以检测是否没有与箱子碰撞而通过的球员在屏幕的另一半。所以我想检测球是否碰到空隙,让球员得分,否则球与箱子碰撞

这是因为您的障碍 contactTestBitMask 正在寻找 Object,而不是 Ball。你想要这个:box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue

鉴于新的变化:

ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue | ColliderType.Gap.rawValue

如果你想让联系人工作,你需要检查间隙值