swift 如何激活模型实体的RealityKit手势?

bqf10yzr  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(142)

在下面的代码中,我创建了一个模型实体,并加载了一个名为“stone”的3d模型。然后将generateCollisionShapes设置为true。然后我应该能够将手势安装到视图中,但我得到一个错误,说我的模型实体不符合类型'HasCollision'。
我需要一些帮助来让这个工作。任何反馈都很感激。

import ARKit
import RealityKit

class Coordinator: NSObject {
    
    weak var view: ARView?
            
    @objc func handleTap(_ recognizer: UITapGestureRecognizer) {

        guard let view = self.view else { return }            
        let tapLocation = recognizer.location(in: view)
        
        let results = view.raycast(from: tapLocation, 
                               allowing: .estimatedPlane, 
                              alignment: .horizontal)
        
        if let result = results.first {
            
            let anchor = AnchorEntity(raycastResult: result)
            
            guard let modelEntity = try? ModelEntity.load(named: "stone") 
            else {
                print("didn't find model")
                return
            }                
            modelEntity.generateCollisionShapes(recursive: true)
            anchor.addChild(modelEntity)                
            view.scene.addAnchor(anchor)                                
            view.installGestures(.all, for: modelEntity)    
        }            
    }        
}
bxfogqkk

bxfogqkk1#

应该使用Entity.loadModel(...)方法而不是ModelEntity.load(...)

guard let modelEntity = try? Entity.loadModel(named: "stone") else { return }

modelEntity.generateCollisionShapes(recursive: true)

arView.installGestures([.all], for: modelEntity as Entity & HasCollision)

附注

  • 将ARView对象声明为UIView的view并不好-将其声明为arView

相关问题