0

我想在我的应用程序中检测两个对象之间的接触。我有一个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 的对象正在屏幕的一半上“下落”,并且“不可见”的间隙可以检测玩家是否在没有与盒子碰撞的情况下通过位于屏幕的另一半。所以我想检测球是否触及间隙,以便球员得分,否则球与盒子碰撞

4

1 回答 1

1

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

鉴于新的变化:

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

如果您想联系工作,您需要检查差距值

于 2015-12-17T18:15:07.053 回答