我从 Sketchfab 购买了 2 个 USDZ 模型。但我不明白为什么行为不同。
第一个模型,我可以使用
ModelEntity
添加 object.model!.mesh.bounds.extents
并存储 object.availableAnimations[0]
struct ImmrsiveView: View {
@State var object: ModelEntity? = nil
@State var animation: AnimationResource? = nil
var body: some View {
RealityView { content in
do {
object = try await ModelEntity(named: "speaker")
if let object {
let objectBound = object.model!.mesh.bounds.extents
object.components.set(CollisionComponent(shapes: [.generateBox(size: objectBound)]))
object.components.set(InputTargetComponent())
animation = object.availableAnimations[0]
content.add(object)
}
}
catch {
print("Error loading the model")
}
}
}
}
但是,当我使用第二个 USDZ 文件时(只需更改实体名称),
object
类型更改为 Entity
,即使加载程序是 ModelEntity.load(named: "object") 并带有警告:内部没有发生“异步”操作“等待”表情。.mesh.bounds.extents
了。碰撞不起作用Entity
,现在 availableAnimations[0] 可以工作了!所以现在代码变成了
struct ImmrsiveView: View {
@State var object: Entity? = nil
@State var animation: AnimationResource? = nil
var body: some View {
RealityView { content in
do {
object = try await ModelEntity.load(named: "object2")
if let object {
// This doesn't work
// let objectBound = object.model!.mesh.bounds.extents
// object.components.set(CollisionComponent(shapes: [.generateBox(size: objectBound)]))
// object.components.set(InputTargetComponent())
animation = object.availableAnimations[0]
content.add(object)
}
}
catch {
print("Error loading the model")
}
}
}
}
问题是......假设有不同的方式加载 USDZ 文件:
请使用
ModelEntity
类型:
import SwiftUI
import RealityKit
struct ContentView: View {
@State var object = ModelEntity()
@State var animation: AnimationResource? = nil
var body: some View {
RealityView { rvc in
do {
object = try await ModelEntity(named: "Man")
object.position.z = -3.0
object.name = "Character"
object.generateCollisionShapes(recursive: false)
object.components.set(InputTargetComponent())
animation = object.availableAnimations[0].repeat()
object.playAnimation(animation!)
rvc.add(object)
print(object.model?.mesh.bounds.extents as Any)
}
catch {
print("Error loading the model")
}
}
.gesture(gesture)
}
var gesture: some Gesture {
TapGesture()
.targetedToEntity(object)
.onEnded {
print($0.entity.name)
}
}
}