【问题标题】:How can I remove specific nodes from a scenekit scene?如何从场景包场景中删除特定节点?
【发布时间】:2023-03-12 12:35:02
【问题描述】:

我使用以下代码,它会检查触摸点,如果点为空,它将添加对象或删除对象。

@objc func didTap(withGestureRecognizer recognizer: UIGestureRecognizer) {

        let tapLocation = recognizer.location(in: sceneView)
        let hitTestResults = sceneView.hitTest(tapLocation)

        guard let node = hitTestResults.first?.node else {

            let hitTestResultsWithFeaturePoints = sceneView.hitTest(tapLocation, types: .featurePoint)

            if let hitTestResultWithFeaturePoints = hitTestResultsWithFeaturePoints.first {

                let translation = hitTestResultWithFeaturePoints.worldTransform.translation

                guard let carScene = SCNScene(named: "car.dae") else { return }
                let carNode = SCNNode()
                let carSceneChildNodes = carScene.rootNode.childNodes
                for childNode in carSceneChildNodes {
                    carNode.addChildNode(childNode)
                }
                carNode.position = SCNVector3(translation.x, translation.y, translation.z)
                carNode.scale = SCNVector3(0.5, 0.5, 0.5)
                sceneView.scene.rootNode.addChildNode(carNode)
            }
            return

        }
    node.removeFromParentNode()
}

但我的对象是由 DAE 文件创建的,它包含很多子节点。 如果我使用node.removeFromParentNode() 它只会删除一个节点

如果我使用以下代码,它将删除屏幕上的所有对象。

sceneView.scene.rootNode.enumerateChildNodes { (existingNode, _) in
        existingNode.removeFromParentNode()
    }

如何从场景包场景中移除特定节点?

【问题讨论】:

    标签: swift nodes scenekit


    【解决方案1】:

    您应该命名您的节点,然后您可以使用该名称将它们过滤掉。

    sceneView.scene.rootNode.childNodes.filter({ $0.name == "yourName" }).forEach({ $0.removeFromParentNode() })
    

    【讨论】:

    • 感谢您的回复,但它不起作用并显示“Extra argument 'withName' in call”错误消息。
    • 对,对不起,我将SpriteKitSceneKit 混淆了。检查编辑的答案。
    • 我尝试使用 sceneView.scene.rootNode.childNodes.filter({ $0.name == "car.dae" }).forEach({ $0.removeFromParentNode() }) ,但它不起作用。我应该更改 didTap 功能吗?
    • 这行不通,因为car.daeSCNScene 不是节点,所以尝试在didTap 函数之外声明carScene,这样你就可以过滤它的childNodes。
    • 对不起,我不知道在 didTap func 之外声明 carScene。我该怎么办?
    【解决方案2】:

    你可以使用:

    func childNode(withName name: String, 
       recursively: Bool) -> SCNNode?
    

    转到文档,https://developer.apple.com/documentation/scenekit/scnnode/1407951-childnode

    【讨论】:

      猜你喜欢
      • 2015-04-28
      • 1970-01-01
      • 2014-09-02
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多