SceneKit_大神03_navigationbar上的3D文字
让学习成为一种习惯
游戏中存在很多的碰撞,比如物体和物体的碰撞,物体和场景的碰撞,在这里我们不深究,碰撞检测的底层实现过程,苹果公司已经帮助我们封装好,我们只需要调用即可!
让学习成为一种习惯
import SceneKit
let scnView = SCNView(frame: self.view.bounds)
scnView.backgroundColor = UIColor.black
self.view.addSubview(scnView)
let scene = SCNScene()
scnView.scene = scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.camera?.automaticallyAdjustsZRange = true
cameraNode.position = SCNVector3(x: 0, y: 10, z: 10)
cameraNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: -Float(M_PI/4))
scnView.scene?.rootNode.addChildNode(cameraNode)
let sphere = SCNSphere(radius: 1)
sphere.firstMaterial?.diffuse.contents = UIColor.red
let sphereNode = SCNNode(geometry: sphere)
sphereNode.position = SCNVector3(x:0,y:2,z:0)
scene.rootNode.addChildNode(sphereNode)
let box = SCNBox(width: 2, height: 2, length: 2, chamferRadius: 0)
box.firstMaterial?.diffuse.contents = UIColor.blue
let boxNode = SCNNode(geometry: box)
boxNode.position = SCNVector3(x:0,y:20,z:0)
scene.rootNode.addChildNode(boxNode)
let floor = SCNFloor()
floor.firstMaterial?.diffuse.contents = "floor.jpg"
let floorNode = SCNNode(geometry: floor)
scene.rootNode.addChildNode(floorNode)
准备工作这是时候就做完了,运行一下
让学习成为一种习惯
接下来说说碰撞的实现思路
SCNView 有个代理SCNSceneRendererDelegate,我们设置它的代理,然后在代理时间自己写算法去检测碰撞,这种方案的确定是要自己写检测算法
scnView.delegate = self
// 实现代理
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval){
print("检测碰撞")
}
首先你应该知道 SCNScene 有个属性叫做physicsWorld(物理世界),physicsWorld对象有个碰撞代理SCNPhysicsContactDelegate
scene.physicsWorld.contactDelegate = self
/// 碰撞代理有三个方法,叫做开始碰撞,碰撞中和结束碰撞
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact){
print(contact)
}
func physicsWorld(_ world: SCNPhysicsWorld, didUpdate contact: SCNPhysicsContact){
print(contact)
}
func physicsWorld(_ world: SCNPhysicsWorld, didEnd contact: SCNPhysicsContact){
print(contact)
}
我们试着给上面的正方体,添加一个向下的行为,让其碰撞球体
让学习成为一种习惯
结论
碰撞代码方法没有被执行,这个是很正常的,因为我们的代理是物理世界的碰撞代理,如果你的行为不是物理世界的行为导致的碰撞,系统是不会处理的,如果非物理世界的行为要使用碰撞,你这个时候,就必须使用第一种方式去检测了。
接下来,我们给地板 球体 和 正方体 同时设置物理身体
floorNode.physicsBody = SCNPhysicsBody.static()
sphereNode.physicsBody = SCNPhysicsBody.kinematic()
boxNode.physicsBody = SCNPhysicsBody.dynamic()
测试也无效,原因不详