1 導入 ARKit
2 授權相機權限
3 創(chuàng)建 sceneView 用來顯示場景
4 配置session ARWorldTrackingConfiguration 獲取后置相機 ARFaceTrackingConfiguration 獲取前置相機 (人臉識別)
sceneView.session.run(configuration)
5 添加3d 物體
func addBox() {
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
let boxNode = SCNNode()
boxNode.geometry = box
boxNode.position = SCNVector3(0, 0, -0.2)
let scene = SCNScene()
scene.rootNode.addChildNode(boxNode)
sceneView.scene = scene
}
創(chuàng)建一個Box惑惶,1 Float = 1 meter易猫。
創(chuàng)建一個node察蹲。node表示物體在三維空間中的位置和坐標。node本身沒有可見的內容。
給node設置一個形狀(Box)。
設置box的位置监透。這個位置相對于camera的,右邊是X正航唆,左邊是X負胀蛮。上面表示Y正,向下表示Y負糯钙。向后表示Z正粪狼,向前表示Z負。
創(chuàng)建一個scene(SceneKit scene)超营,將box添加到場景中去鸳玩。
將sceneView的scene設置為顯示剛剛創(chuàng)建的場景。
6 點擊屏幕添加模型 點擊模型刪除
@objc func didTap(withGestureRecognizer recognizer: UIGestureRecognizer) {
let tapLocation = recognizer.location(in: sceneView)
let hitTestResults = sceneView.hitTest(tapLocation)
guard let node = hitTestResults.first?.node else {
let hitTestResultsWithFeaturePoints = sceneView.hitTest(tapLocation, types: .featurePoint)
if let hitTestResultWithFeaturePoints = hitTestResultsWithFeaturePoints.first {
let translation = hitTestResultWithFeaturePoints.worldTransform.translation
addBox(x: translation.x, y: translation.y, z: translation.z)
}
return
}
node.removeFromParentNode()
}