ARKit Swift中未检测到SCNNode之间的冲突

时间:2019-06-30 18:10:37

标签: ios swift scenekit arkit

我希望子弹与飞船相撞,但是即使设置了委托和物理物体碰撞属性,也不会调用 func physicsWorld(_ world: SCNPhysicsWorld, didEnd contact: SCNPhysicsContact)

这是我的代码:

class Bullet: SCNNode {
    override init () {
        super.init()
        let sphere = SCNSphere(radius: 0.020)
        sphere.materials.first?.diffuse.contents =  UIColor.red
        self.geometry = sphere
        let shape = SCNPhysicsShape(geometry: sphere, options: nil)
        self.physicsBody = SCNPhysicsBody(type: .dynamic, shape: shape)
        self.physicsBody?.isAffectedByGravity = false
        self.physicsBody?.categoryBitMask = CollisionCategory.bullets.rawValue
        self.physicsBody?.contactTestBitMask = CollisionCategory.enemy.rawValue
        self.physicsBody?.collisionBitMask = CollisionCategory.enemy.rawValue
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

struct CollisionCategory: OptionSet {
    let rawValue: Int
    static let bullets  = CollisionCategory(rawValue: 1 << 1) // 00...01
    static let enemy = CollisionCategory(rawValue: 1 << 0) // 00..10
}
class ARViewController: UIViewController, ARSCNViewDelegate, SCNPhysicsContactDelegate {

    @IBOutlet var sceneView: ARSCNView!
    var enemyNodes = [SCNNode]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set the view's delegate
        sceneView.delegate = self

        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true
        sceneView.scene.physicsWorld.contactDelegate = self
       setupEnemies()

    }

func setupEnemies() {
        guard let enemyNode = SCNScene(named: "art.scnassets/ship.scn")?.rootNode.childNodes.first else { return }

        enemyNode.position = getRandomVector()
        enemyNode.name = "enemy"
        enemyNode.physicsBody?.categoryBitMask = CollisionCategory.enemy.rawValue
        enemyNode.physicsBody?.contactTestBitMask =  CollisionCategory.bullets.rawValue
        enemyNode.physicsBody?.collisionBitMask = CollisionCategory.bullets.rawValue
        enemyNodes.append(enemyNode)
        sceneView.scene.rootNode.addChildNode(enemyNode)
    }

func physicsWorld(_ world: SCNPhysicsWorld, didEnd contact: SCNPhysicsContact) {
        print("did begin contact", contact.nodeA.physicsBody!.categoryBitMask, contact.nodeB.physicsBody!.categoryBitMask)
}
}

我不知道我要去哪里错了。

1 个答案:

答案 0 :(得分:0)

我没有为Mo Reza指出的敌人节点设置PhysicsBody。我要做的就是:

self.physicsBody = SCNPhysicsBody(type: .static, shape: nil)

它奏效了。