用ARKit做碰撞检测,其实也就是做3D碰撞检测。3D碰撞检测需要涉及到比较复杂的数学知识,还好SceneKit给我们提供了很多方便的方法来实现3D碰撞检测。接下来,我们用ARKit来实现一个简单的3D碰撞检测
一、创建工程
我们选择用Swift语言
二、将需要的模型文件拖进工程
模型放在art.scnassets文件夹
三、创建egg节点
创建egg节点,给节点添加物理属性
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.showsStatistics = true
let scene = SCNScene(named: "art.scnassets/egg.scn")!
let eggNode = scene.rootNode.childNode(withName: "egg", recursively: false)
//节点位置
eggNode?.position = SCNVector3(5,0,-40)
//创建physicBody
let body = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(node: eggNode!, options: nil))
//是否受重力影响
body.isAffectedByGravity = false
eggNode?.physicsBody = body
//物理特性
eggNode?.physicsBody?.categoryBitMask = 3
eggNode?.physicsBody?.contactTestBitMask = 2
sceneView.scene.rootNode.addChildNode(eggNode!)
sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints,ARSCNDebugOptions.showWorldOrigin]
//设置 SCNPhysicsContactDelegate
sceneView.scene.physicsWorld.contactDelegate = self
}
四、点击屏幕创建子弹节点
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let geometry = SCNSphere(radius: 0.1)
geometry.firstMaterial?.diffuse.contents = UIColor.red
let buttleNode = SCNNode(geometry: geometry)
guard let sceneView = self.view as? ARSCNView else {
return
}
guard let pointView = sceneView.pointOfView else {
return
}
let transform = pointView.transform
//子弹射向的位置
buttleNode.position = SCNVector3((-transform.m31-transform.m41),(-transform.m32-transform.m42),(-transform.m33-transform.m43))
//创建钢体
let body = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: buttleNode, options: nil))
//是否受重力影响
body.isAffectedByGravity = false
buttleNode.physicsBody = body
//子弹飞行速度
buttleNode.physicsBody?.applyForce(SCNVector3( (-transform.m31) * 50,(- transform.m32) * 50,(-transform.m33) * 50), asImpulse: true)
buttleNode.physicsBody?.categoryBitMask = 2
buttleNode.physicsBody?.contactTestBitMask = 3
sceneView.scene.rootNode.addChildNode(buttleNode)
}
五、实现SCNPhysicsContactDelegate
var Target: SCNNode? //碰撞之後的結果
// 當被添加了 physicsBody 的節點 相互碰觸的時候 調用這個方法
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact){
let nodeA = contact.nodeA //第一次子弹
let nodeB = contact.nodeB //第二个蛋
if nodeA.physicsBody?.contactTestBitMask == 2 {
Target = nodeA //没射中 留下的是子弹
}else if nodeB.physicsBody?.contactTestBitMask == 3{
Target = nodeB //射中了 留下的是蛋
}
//这个效果通过创建scnp文件选择
let confetti = SCNParticleSystem(named: "art.scnassets/smoke.scnp", inDirectory: nil)
如下图:
confetti?.loops = false
confetti?.particleLifeSpan = 4
confetti?.emitterShape = Target?.geometry
let confetNode = SCNNode()
confetNode.addParticleSystem(confetti!) //节点上添加的特效
confetNode.position = contact.contactPoint //两个节点碰撞后作用的地方
sceneView.scene.rootNode.addChildNode(confetNode)
Target?.removeFromParentNode()
}
六、运行
好了,一个ARKit碰撞射击游戏就这么简单的完成,有没有很happy
效果图:
撞击前是一个完整的蛋
撞击后变为一缕青烟