我目前正在开发一个iOS应用程序,使用ARKit和SceneKit进行增强现实。我有一个问题,而加载一个。usdz模型到场景。我可以正确地将其加载到场景中,但是,当我尝试在点击它后获得节点名称(我在其中加载了。usdz模型)时,它返回。usdz名称而不是我给它的名称。
我用来加载。usdz模型的代码是:let mdlAsset = MDLAsset(url: urlPath)
mdlAsset.loadTextures()
let asset = mdlAsset.object(at: 0) // extract first object
var assetNode = SCNNode(mdlObject: asset)
assetNode = SCNNode(mdlObject: asset)
assetNode.name = "Node-2"
sceneView.scene.rootNode.addChildNode(assetNode)
要捕获节点上的点击,代码如下:
@objc func handleTap(recognizer: UITapGestureRecognizer){
let location = recognizer.location(in: sceneView)
let results = sceneView.hitTest(location, options: nil)
guard recognizer.state == .ended else { return }
if results.count > 0 {
let result = results[0] as SCNHitTestResult
let node = result.node
print(node.name)
}
}
正如我之前提到的,当我点击对象时,它会打印可选("Sphere_0"值,可以在模型详细信息页面的右上角找到。我期望的正确值是"Node-2"
您的USDZ模型的名称没有被覆盖。这是SceneKit命中测试和场景层次结构的特性。当您执行命中测试搜索时,SceneKit沿着您指定的射线查找SCNGeometry
对象(不是主节点)。因此,一旦完成命中测试,您所需要做的就是找到相应的父节点。
试试这个代码:
import SceneKit.ModelIO
class GameViewController: UIViewController {
var sceneView: SCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView = (self.view as! SCNView)
let scene = SCNScene(named: "art.scnassets/ship.scn")!
sceneView.scene = SCNScene()
sceneView.backgroundColor = .black
let recog = UITapGestureRecognizer(target: self, action: #selector(tap))
sceneView.addGestureRecognizer(recog)
// ASSET
let mdlAsset = MDLAsset(scnScene: scene)
let asset = mdlAsset.object(at: 0)
let node = SCNNode(mdlObject: asset.children[0])
node.name = "Main-Node-Name" // former "ship"
node.childNodes[0].name = "SubNode-Name" // former "shipMesh"
node.childNodes[0].childNodes[0].name = "Geo-Name" // former "Scrap_MeshShape"
sceneView.scene?.rootNode.addChildNode(node)
}
}
你的hit-testing method:
extension GameViewController {
@objc func tap(recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: sceneView)
let results = sceneView.hitTest(location)
guard recognizer.state == .ended else { return }
if results.count > 0 {
let result = results[0] as SCNHitTestResult
let node = result.node
print(node.name!) // Geo-Name
print(node.parent!.name!) // SubNode-Name
print(node.parent!.parent!.name!) // Main-Node-Name
}
}
}