首页 > 解决方案 > 如何在 Swift Scenekit 中切换对象负载?

问题描述

我想使用 iOS SceneKit 加载对象。

以及如何卸载加载的对象并重新加载另一个对象?

通过参考下面的代码,我成功加载了对象。

func sceneSetup() {

    if let filePath = Bundle.main.path(forResource: "Smiley", ofType: "scn") {
        let referenceURL = URL(fileURLWithPath: filePath)

        self.contentNode = SCNReferenceNode(url: referenceURL)
        self.contentNode?.load()
        self.head.morpher?.unifiesNormals = true // ensures the normals are not morphed but are recomputed after morphing the vertex instead. Otherwise the node has a low poly look.
        self.scene.rootNode.addChildNode(self.contentNode!)
    }
    self.faceView.autoenablesDefaultLighting = true

    // set the scene to the view
    self.faceView.scene = self.scene

    // allows the user to manipulate the camera
    self.faceView.allowsCameraControl = false

    // configure the view
    self.faceView.backgroundColor = .clear
}

但我不知道如何加载和切换多个对象。

我在项目中添加了 testScene.scn 并添加了如下代码,但只加载了第一个指定的对象。

var charaSelect = "Smiley"

//tapEvent(ViewDidLoad)
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FaceGeoViewController.tapped(_:)))
    tapGesture.delegate = self
    self.view.addGestureRecognizer(tapGesture)

//tap
 @objc func tapped(_ sender: UITapGestureRecognizer)
 {
    self.charaSelect = "testScene"
 }

func sceneSetup() {

    if let filePath = Bundle.main.path(forResource: self.charaSelect, ofType: "scn") {
        let referenceURL = URL(fileURLWithPath: filePath)

        self.contentNode = SCNReferenceNode(url: referenceURL)
        self.contentNode?.load()
        self.head.morpher?.unifiesNormals = true // ensures the normals are not morphed but are recomputed after morphing the vertex instead. Otherwise the node has a low poly look.
        self.scene.rootNode.addChildNode(self.contentNode!)
    }
    self.faceView.autoenablesDefaultLighting = true

    // set the scene to the view
    self.faceView.scene = self.scene

    // allows the user to manipulate the camera
    self.faceView.allowsCameraControl = false

    // configure the view
    self.faceView.backgroundColor = .clear
}

我应该怎么办?

标签: swiftscenekitarkit

解决方案


我将在这里解释这个概念,但如果您可能需要将这些东西视为一个完整的项目,欢迎您参考我在 Apple Education,2019 年出版的“App Development with Swift”</a>一书中遵循的代码,特别是第 3A 章末尾的引导项目。

您可以在下面看到示例屏幕截图。在应用程序中,您可以通过触摸 SceneView 上的空白位置或当您的触摸与另一个对象(平面)发生碰撞来添加元素。此外,还有一个删除对象的逻辑

在此处输入图像描述

因此,基本上,能够从场景中删除节点的一​​种方法是ViewController使用特殊的数组跟踪它们var placedNodes = [SCNNode]()。这样您就可以清除所有节点的视图(例如,通过创建按钮操作“清除”)

您可能从 Apple 的开发人员那里了解到的另一个不错的补充是不使用轻击手势识别器,而是通过覆盖touchesBegan / touchesMoved,这可以让您更灵活地使用触摸手势,特别是,您可以获取它的位置通过调用 SceneView touch.location(in: sceneView)

因此,touchesBegan/touchesMoved允许您定位用户点击的位置。这可用于在 SceneView 上添加/删除对象

希望这会有所帮助!


推荐阅读