碰撞检测SceneKit Swift

时间:2016-05-27 22:32:53

标签: ios swift scenekit

我使用委托SCNPhysicsContactDelegate构建了一个带碰撞检测的应用程序。我尝试检测与SCNPhysicsContactDelegate委托的冲突,但它不起作用。

什么是狼人??

这是我的代码

let CollisionCategorySpaceMan = 1
let CollisionCategoryEnemy = 2

func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact) {
    if contact.nodeB.physicsBody!.categoryBitMask == CollisionCategoryEnemy {
        print("Enemy HIT!--------")
    }
}




  override func viewDidLoad() {
        super.viewDidLoad()

let mainScene = createMainScene()

        mainScene.physicsWorld.contactDelegate = self

        mainScene.physicsWorld.gravity = SCNVector3Make(0, 0, 0)



        sceneView = self.view as! GameView
        sceneView.scene = mainScene
        sceneView.delegate = self

    }

这是敌人

func setupEnemy(){
        space = space - 300
        let football2 = SCNScene(named: "art.scnassets/k.scn")
        let football21 = football2!.rootNode.childNodeWithName("football2", recursively: false)
        football21!.name = "Enemy"
        football21!.physicsBody = SCNPhysicsBody(type: .Dynamic, shape: nil)
        football21!.physicsBody!.categoryBitMask = CollisionCategoryEnemy
        football21!.physicsBody!.collisionBitMask = CollisionCategorySpaceMan
        football21!.position = SCNVector3(x: 0, y: 0, z: Float(space))
        sceneView.scene!.rootNode.addChildNode(football21!)
    }

这是英雄

func createMainScene() -> SCNScene {
        let scene = SCNScene(named: "art.scnassets/football.scn")
        spaceManNode = scene!.rootNode.childNodeWithName("football", recursively: false)

        spaceManNode!.physicsBody = SCNPhysicsBody(type: .Dynamic, shape: nil)
        spaceManNode!.physicsBody!.categoryBitMask = CollisionCategorySpaceMan
        spaceManNode!.physicsBody!.contactTestBitMask = CollisionCategoryEnemy
        spaceManNode.name = "SpaceMan"

        setupLighting(scene!)
        setupCameras(scene!)

        return scene!
    }

2 个答案:

答案 0 :(得分:2)

从iOS 9开始,您必须明确设置physicsBody的“contactTestBitMask”以获取联系人通知。看起来setupEnemy()中缺少这个。我的游戏中的碰撞在iOS 8中运行良好但在iOS 9上停止工作,直到我找到这篇文章:Why Contact Delegate isn't called in SceneKit?

希望这有帮助!

答案 1 :(得分:0)

在这种情况下,我发现了2条缺失的行:

您的敌人目标或类似的目标...

physicsBody?.categoryBitMask = PhysicsCategory.enemy // your enemy category (lets say 1)
physicsBody?.collisionBitMask = PhysicsCategory.player (with what can report collision lets say 2

您的英雄:

physicsBody?.categoryBitMask = PhysicsCategory.player  // the category is 2
physicsBody?.collisionBitMask = PhysicsCategory.enemy | PhysicsCategory.ball // can report collision with 1 and 3        
physicsBody?.contactTestBitMask = PhysicsCategory.enemy | PhysicsCategory.ball // when hitTest performed detect collision with 1 and 3

希望这会有所帮助, 问候