ios - 如何制作跟随相机的模型

标签 ios swift 3d scenekit arkit

我想添加一个跟随 iOS 设备相机的 3D 模型。到目前为止,我的代码还不够,因为没有轮换。更重要的是,我觉得 ARKit 中有更简单的解决方案,比如 SceneKit,所以我想寻求你的帮助:

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!
}

提前致谢!

最佳答案

如果一个节点被添加为包含相机的节点的子节点,它将与相机一起移动。您可以使用 sceneView.pointOfView? 获取包含相机的节点,并使用 addChildNode(child:) 添加 pistolNode 作为其子节点之一方法。

// 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

关于ios - 如何制作跟随相机的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857705/

相关文章:

ios - X 轴值重叠 - iOS 图表

ios - 仅在 Testflight 构建时应用程序崩溃

javascript - 如何旋转相机使其面向球体上的点(Three.js)

ios - 检查创建的指针对象是否小于今天 Parse.com

c++ - 为什么这个 XMVector3Transform 调用没有返回正确的结果?

postgresql - 如何计算 Postgresql 中 3D 对象的体积?

ios - 我可以使用 Alamofire 检查 HTTP 服务器 URL 端点的可达性吗?

ios - AVMutableVideoCompositionInstruction 在 AVMutableVideoComposition 中被忽略

ios - 阻止 SKSpriteNode 离开 View (Swift)

Swift iAP 错误(Objective-C 方法 * 与可选要求方法冲突)