英文:
How to activate RealityKit gestures for Model entity?
问题
在下面的代码中,我创建了一个模型实体并加载了一个名为"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("没有找到模型")
return
}
modelEntity.generateCollisionShapes(recursive: true)
anchor.addChild(modelEntity)
view.scene.addAnchor(anchor)
view.installGestures(.all, for: modelEntity)
}
}
}
英文:
In the code below, I create a model entity and load a 3d model named "stone". I then set generateCollisionShapes
to true. I should then be able to install gestures to the view but I'm getting an error saying my model entity doesn't conform to the type 'HasCollision'.
I need some help getting this to work. Any feedback is appreciated.
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)
}
}
}
答案1
得分: 1
你应该使用 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”。
英文:
You should use Entity.loadModel(...)
method instead of ModelEntity.load(...)
guard let modelEntity = try? Entity.loadModel(named: "stone") else { return }
modelEntity.generateCollisionShapes(recursive: true)
arView.installGestures([.all], for: modelEntity as Entity & HasCollision)
P. S.
- It's not good to declare an ARView object as UIView's
view
– declare it asarView
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论