SKPhysics工作不正常?

时间:2015-07-04 17:18:22

标签: swift sprite-kit skphysicsbody

struct PhysicsCategory {
    static let None      : UInt32 = 0
    static let All       : UInt32 = UInt32.max
    static let planet    : UInt32 = 0b1    
    static let rocket    : UInt32 = 0b10 }

planet.physicsBody = SKPhysicsBody(circleOfRadius: planet.size.width / 2)
planet.physicsBody?.dynamic = true planet.physicsBody?.categoryBitMask = PhysicsCategory.planet
planet.physicsBody?.contactTestBitMask = PhysicsCategory.rocket 
planet.physicsBody?.collisionBitMask = PhysicsCategory.None

func planetCollidedWithRocket(rocket: SKSpriteNode, planet: SKSpriteNode) {
    println("collision planet") }



 func didBeginContact(contact: SKPhysicsContact) {
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
        } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA }

        if ((firstBody.categoryBitMask & PhysicsCategory.planet != 0) &&
            (secondBody.categoryBitMask & PhysicsCategory.rocket != 0)) {
            planetCollidedWithRocket(firstBody.node as! SKSpriteNode, planet: secondBody.node as! SKSpriteNode)}

我目前正在使用它来为我的游戏添加碰撞检测(我只采取了我认为相关的代码)。我第一次在模拟器上运行游戏时效果很好,我在场景中添加了一个游戏到planetCollidedWithRocket方法。但是我今天再次测试了它,并且出于某种原因,游戏在没有碰撞的情况下检测到火箭和行星之间的碰撞!谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的联系人设置不正确。这就是你所拥有的,以及它所转化的内容:

if((firstBody.categoryBitMask & PhysicsCategory.planet !=0)
// This is checking if the firstBody *has* a categoryBitMask, but it is not evaluating what it is. 
// In addition to that, it is requiring that the PhysicsCategory.planet does not equal zero, which it doesn't. 
// This would evaluate to true every time, no matter what.
// It is also requiring that...


&& (secondBody.categoryBitMask & PhysicsCategory.rocket != 0))
// This is checking if the secondBody *has* a categoryBitMask, but it is not evaluating what it is.
// In addition to that, it is requiring that the PhysicsCategory.planet does not equal zero, which it doesn't.
// This would evaluate to true every time, no matter what.

你需要做的是检查你的categoryBitMask 等于你的一个PhysicsCategory变量,这样当行星和火箭接触时,某些东西会被评估为真。试试这个:

if ((firstBody.categoryBitMask == PhysicsCategory.planet) &&
    (secondBody.categoryBitMask == PhysicsCategory.rocket)){

// Code Here

}

或者,既然您知道PhysicsCategory结构中的硬编码数字,那么您可以评估为硬数字:

if ((firstBody.categoryBitMask == 1) &&
    (secondBody.categoryBitMask == 2)){

// Code Here

}

这样做是检查物理实体的categoryBitMask在接触时是否等于某些数字。如果他们这样做,会发生一些事情,如果没有,就什么都不会发生。