下面的我的快速代码使用func touchesBegan将scn对象放置在ARKit视图中。问题在于它仅放置对象一次。我想以某种方式创建代码,使用户可以选择任何区域来放置scn对象,并且它也可以根据需要多次放置它。
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//Handle the shooting
guard let frame = sceneView.session.currentFrame else { return }
let camMatrix = SCNMatrix4(frame.camera.transform)
let direction = SCNVector3Make(-camMatrix.m31 * 5.0, -camMatrix.m32 * 10.0, -camMatrix.m33 * 5.0)
let position = SCNVector3Make(camMatrix.m41, camMatrix.m42, camMatrix.m43)
let scene = SCNScene(named: "art.scnassets/dontCare.scn")!
sceneView.scene = scene
}
}
尝试一下
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard
let touchPosition = touches.first?.location(in: sceneView),
let hitTest = sceneView.hitTest(touchPosition, types: .featurePoint).first
else {return}
let sphere = SCNNode(geometry: SCNSphere(radius: 0.01))
sphere.simdTransform = hitTest.worldTransform
sceneView.scene.rootNode.addChildNode(sphere)
}
}