我想添加一个跟随iOS设备相机的3D模型。我的代码到目前为止,但由于没有轮换,这还不够。更重要的是,我觉得SceneKit
内的ARKit
更容易解决,所以我会请求你的帮助:
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
var timer = Timer()
var pistolNode = SCNNode()
override func viewDidLoad()
{
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Create a new scene
let pistol = SCNScene(named: "art.scnassets/pistol.dae")!
pistolNode = pistol.rootNode.childNode(withName: "pistol", recursively: true)!
pistolNode.position = SCNVector3Make(0, -0.3, -0.5)
let scene = SCNScene()
scene.rootNode.addChildNode(pistolNode)
// Set the scene to the view
sceneView.scene = scene
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.restartSession)), userInfo: nil, repeats: true)
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
@objc func restartSession()
{
pistolNode.position = SCNVector3Make((sceneView.pointOfView?.position.x)!, (sceneView.pointOfView?.position.y)! - 0.3, (sceneView.pointOfView?.position.z)! - 0.5)
}
@IBOutlet weak var info: UILabel!
}
提前致谢!
答案 0 :(得分:1)
如果节点被添加为包含摄像机的节点的子节点,则节点将与摄像机一起移动。您可以使用sceneView.pointOfView?
获取包含相机的节点,并使用pistolNode
方法将addChildNode(child:)
添加为其子节点之一。
// Create a new scene
let pistol = SCNScene(named: "art.scnassets/pistol.dae")!
pistolNode = pistol.rootNode.childNode(withName: "pistol", recursively: true)!
pistolNode.position = SCNVector3Make(0, -0.3, -0.5)
// let scene = SCNScene()
sceneView.pointOfView?.addChildNode(pistolNode)
// Set the scene to the view
sceneView.scene = pistol