看到一個大牛的blog,點擊屏幕擊打物品,做了一點研究,和大家分享一下,屏幕截圖如下:
image.png
首先,需要一個被擊打對象
暫時先用一個BOX吧(就是因為簡單),給這個BOX設置屬性,具體可以參看基本碰撞測試,有幾個需要注意的點:
- isAffectedByGravity表示當前物體不受重力影響。
- categoryBitMask標示自己。
- contactTestBitMask標示可以和自己碰撞的物體。
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
self.geometry = box
let shape = SCNPhysicsShape(geometry: box, options: nil)
self.physicsBody = SCNPhysicsBody(type: .dynamic, shape: shape)
self.physicsBody?.isAffectedByGravity = false
//標識自己和碰撞的對方
self.physicsBody?.categoryBitMask = CollisionCategory.ship.rawValue
self.physicsBody?.contactTestBitMask = CollisionCategory.bullets.rawValue
//加上紋理
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: "galaxy")
self.geometry?.materials = [material, material, material, material, material, material]
為了放在正前方,x,y軸在(-0.5~0.5)之間,z軸為-1。
let posX = floatBetween(-0.5, and: 0.5)
let posY = floatBetween(-0.5, and: 0.5 )
cubeNode.position = SCNVector3(posX, posY, -1) // SceneKit/AR coordinates
image.png
其次,點擊屏幕,新建一枚子彈
增加點擊事件
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTapGesture))
//設置手勢點擊數(shù),雙擊:點1下
tapGesture.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapGesture)
新建一枚子彈,和被打擊對象差不多,唯一的區(qū)別是categoryBitMask和contactTestBitMask剛好相反。
let sphere = SCNSphere(radius: 0.025)
self.geometry = sphere
let shape = SCNPhysicsShape(geometry: sphere, options: nil)
self.physicsBody = SCNPhysicsBody(type: .dynamic, shape: shape)
self.physicsBody?.isAffectedByGravity = false
// see http://texnotes.me/post/5/ for details on collisions and bit masks
self.physicsBody?.categoryBitMask = CollisionCategory.bullets.rawValue
self.physicsBody?.contactTestBitMask = CollisionCategory.ship.rawValue
// add texture
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: "bullet_texture")
self.geometry?.materials = [material]
發(fā)射子彈
首先需要知道當前攝像頭的位置,根據(jù)ARCamera的位置可以計算出從攝像頭發(fā)射子彈的位置和方向:
位置比較好理解:就是 SCNVector3(mat.m41, mat.m42, mat.m43),這個是世界坐標系的位置。
方向就需要好好理解一下,其實是原點(0,0,0)到攝像頭點的方向。
func getUserVector() -> (SCNVector3, SCNVector3) { // (direction, position)
if let frame = self.sceneView.session.currentFrame {
let mat = SCNMatrix4FromMat4(frame.camera.transform) // 4x4 transform matrix describing camera in world space
let dir = SCNVector3(-1 * mat.m31, -1 * mat.m32, -1 * mat.m33) // orientation of camera in world space
let pos = SCNVector3(mat.m41, mat.m42, mat.m43) // location of camera in world space
return (dir, pos)
}
return (SCNVector3(0, 0, -1), SCNVector3(0, 0, -0.2))
}
發(fā)射子彈,其實就是對子彈作用力,力的位置就是攝像頭的位置,方向就是攝像頭的方向。
let (direction, position) = self.getUserVector()
bulletsNode.position = position // SceneKit/AR coordinates are in meters
let bulletDirection = direction
bulletsNode.physicsBody?.applyForce(bulletDirection, asImpulse: true)
sceneView.scene.rootNode.addChildNode(bulletsNode)
子彈擊中方塊效果
基本碰撞測試里介紹過可以用代理處理碰撞的過程。
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {
if contact.nodeA.physicsBody?.categoryBitMask == CollisionCategory.ship.rawValue || contact.nodeB.physicsBody?.categoryBitMask == CollisionCategory.ship.rawValue {
print("Hit ship!")
//移除子彈
self.removeNodeWithAnimation(contact.nodeB, explosion: false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
//移除方塊,帶爆炸效果
self.removeNodeWithAnimation(contact.nodeA, explosion: true)
//新的方塊
self.addNewShip()
})
}
}
爆炸效果的實現(xiàn)如下,這里通過一個SCNP文件new一個SCNParticleSystem對象,該對象負責SCNNode的動畫效果。
func removeNodeWithAnimation(_ node: SCNNode, explosion: Bool) {
if explosion {
let particleSystem = SCNParticleSystem(named: "explosion", inDirectory: nil)
let systemNode = SCNNode()
systemNode.addParticleSystem(particleSystem!)
// place explosion where node is
systemNode.position = node.position
sceneView.scene.rootNode.addChildNode(systemNode)
}
// remove node
node.removeFromParentNode()
}
廢話不說了,直接看代碼,希望喜歡的人star支持一下。
demo地址