Swift SpriteKit物理碰撞问题

时间:2014-11-27 23:28:41

标签: swift physics

我正在制作一个简单的基于物理的游戏。除碰撞检测外,一切正常。感觉就像被忽略的didBeginContact方法一样。

我尝试了几种配置" PhysicsCategory"的方法。 struct(甚至使用枚举)和bodyA / bodyB联系语句的几种形式。

我完全没有想法。我可以让2个物体碰撞,但它们只会相互反弹。没有错误,也没有记录到控制台。我希望我犯了一个我忽略的微不足道的错误。

以下是所有相关代码。如果它很重要...在didMoveToView

中调用setupPhysics()

PhysicsCategory Struct

struct PhysicsCategory {
static let None: UInt32 = 0
static let Fish: UInt32 = 0b1
static let Bird: UInt32 = 0b10
static let BottomEdge: UInt32 = 0b100}    

物理设置方法

//MARK: - Physics Methods
func setupPhysics() {
    /* Physics World */
    physicsWorld.gravity = CGVectorMake(0, -9.8)
    physicsWorld.contactDelegate = self
    physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)

/* Bottom Collision Rect */
    let bEdge = CGRect(x: CGPointZero.x, y: CGPointZero.y, width: size.width, height: size.height * 0.005)
    let bottomEdge = SKShapeNode(rect: bEdge)
    bottomEdge.physicsBody = SKPhysicsBody(edgeLoopFromRect: bEdge)
    bottomEdge.physicsBody!.categoryBitMask = PhysicsCategory.BottomEdge
    bottomEdge.physicsBody!.collisionBitMask  = PhysicsCategory.Fish
    bottomEdge.physicsBody!.dynamic = false
    gameLayer.addChild(bottomEdge)

    /* Fish */
    fish.physicsBody = SKPhysicsBody(circleOfRadius: blowfish.size.height / 2.1)
    fish.physicsBody!.allowsRotation = false
    fish.physicsBody!.categoryBitMask = PhysicsCategory.Fish
    fish.physicsBody!.collisionBitMask = PhysicsCategory.Bird | PhysicsCategory.BottomEdge

    /* Left Random Bird */
    randomLeftBird.physicsBody = SKPhysicsBody(rectangleOfSize: randomLeftBird.size)
    randomLeftBird.physicsBody!.affectedByGravity = false
    randomLeftBird.physicsBody!.allowsRotation = false
    randomLeftBird.physicsBody!.categoryBitMask = PhysicsCategory.Bird
    randomLeftBird.physicsBody!.collisionBitMask = PhysicsCategory.Fish

    /* Random Right Bird */
    randomRightBird.physicsBody = SKPhysicsBody(rectangleOfSize: randomRightBird.size)
    randomRightBird.physicsBody!.affectedByGravity = false
    randomRightBird.physicsBody!.allowsRotation = false
    randomRightBird.physicsBody!.categoryBitMask = PhysicsCategory.Bird
    randomRightBird.physicsBody!.collisionBitMask = PhysicsCategory.Fish
}

didBeginContact Setup

func didBeginContact(contact: SKPhysicsContact!) {
    let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    if collision == PhysicsCategory.Fish | PhysicsCategory.Bird {
        println("COLLISON WITH BIRD!")
        updateLives()
    } else if collision == PhysicsCategory.Fish | PhysicsCategory.BottomEdge {
        println("EPIC FAIL!")
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您的代码中没有使用contactTestBitMask。那个控制你是否收到联系代表消息 - collisionBitMask只控制它们是否发生碰撞(反弹)。

这些是独立的,因此即使对于不互相反弹的类别,您也可以获得联系委托消息,但这意味着您也可以发生不发送消息的冲突。 (如果您不希望游戏逻辑适用于各种类型的碰撞,那将是一件好事。)您需要的任何联系消息都需要明确请求。