SceneKit Swift 2.0碰撞检测(SCNPhysicsContactDelegate)

时间:2015-09-27 20:29:27

标签: swift delegates collision detection scenekit

我已经使用委托SCNPhysicsContactDelegate构建了一个带碰撞检测的应用程序。现在我正在使用Swift 2.0和Xcode 7,我尝试检测与SCNPhysicsContactDelegate委托的冲突,但它不起作用。 我做错了什么?代码下方:

let CubeType = 1
let PlayerType = 2
class GameViewController: UIViewController, SCNSceneRendererDelegate,SCNPhysicsContactDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    let scnView = self.view as! SCNView
    scnView.scene = SCNScene()
    scnView.scene?.physicsWorld.contactDelegate = self
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    cameraNode.position = SCNVector3(x: 0, y: 0, z: 5)
    scnView.scene?.rootNode.addChildNode(cameraNode)  
    scnView.autoenablesDefaultLighting = true
    scnView.allowsCameraControl = true
    scnView.showsStatistics = true
    scnView.backgroundColor = UIColor.blackColor()

    let g = SCNBox(width: 0.5, height: 0.5, length: 0.5, chamferRadius: 0)
    let n = SCNNode(geometry: g)
    n.physicsBody = SCNPhysicsBody(type: .Kinematic, shape: SCNPhysicsShape(geometry: g, options: nil))
    n.physicsBody?.categoryBitMask = CubeType
    n.physicsBody?.collisionBitMask = PlayerType
    n.position = SCNVector3Make(5, 0, 0)
    scnView.scene?.rootNode.addChildNode(n)

    let playerGeometry = SCNSphere(radius: 1)
    let playerNode = SCNNode(geometry: playerGeometry)
    playerNode.position = SCNVector3Zero
    playerNode.physicsBody = SCNPhysicsBody(type: .Kinematic, shape: SCNPhysicsShape(geometry: playerGeometry, options:nil))

    playerNode.physicsBody?.categoryBitMask = PlayerType
    playerNode.physicsBody?.collisionBitMask = CubeType
    scnView.scene?.rootNode.addChildNode(playerNode)
    let moveAction = SCNAction.moveTo(n.position, duration: 3)
    playerNode.runAction(moveAction)
}

func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact) {
    print("-> didBeginContact")
}

func physicsWorld(world: SCNPhysicsWorld, didEndContact contact: SCNPhysicsContact) {
    print("-> didEndContact")
}

func physicsWorld(world: SCNPhysicsWorld, didUpdateContact contact: SCNPhysicsContact) {
    print("-> didupdatecontact")
}

1 个答案:

答案 0 :(得分:1)

两个节点都缺少.contactTestBitMask属性:

n.physicsBody?.contactTestBitMask = PlayerType
playerNode.physicsBody?.contactTestBitMask = CubeType