如何在 Swift Scenekit 中切换对象加载?

How to switch object load in Swift Scenekit?

我想使用 iOS SceneKit 加载对象。

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

我参考代码below.

加载对象成功
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
}

我该怎么办?

我将在这里解释这个概念,但如果您可能需要将这些东西视为一个完整的项目,欢迎您参考 code that I followed from a book “App Development with Swift” Apple Education,2019,特别是最后的 Guided Project第 3A 章。

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

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

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

来获取它在 SceneView 中的位置

因此,touchesBegan/touchesMoved 允许您定位用户点击的位置。这可能用于 SceneView

上的 adding/removing 个对象

希望对您有所帮助!