我尝试使用 DragGesture 旋转 Apple Vision Pro 的 Model3D。 为此,我只需向角度对象添加度数,它工作正常,但它只能向左或向右旋转,而不是同时旋转。
所以我已经能够检测左/右手势并添加或删除角度。 但由于那里旋转效果不佳,当我仍在向左拖动时,方向可能会变为向右。
@State var rotation: Angle = .zero
@State var previousLocation: CGPoint = .zero
var rotateGesture: some Gesture {
DragGesture()
.targetedToAnyEntity()
.onChanged { value in
if (previousLocation == .zero) {
previousLocation = value.location
}
if (previousLocation.x > value.location.x) {
rotation.degrees -= 1.0
} else {
rotation.degrees += 1.0
}
previousLocation = value.location
}
}
像这样将旋转应用于 3D 模型
.gesture(rotateGesture)
.rotation3DEffect(rotation, axis: .y)
有谁知道出了什么问题或者我错过了什么?
您的问题似乎与万向节锁有关。为了防止您遇到的行为,请在 RealityView 中使用模型的
orientation
属性,而不是 Model3D 视图的 .rotation3DEffect()
修饰符。
import SwiftUI
import RealityKit
struct ContentView: View {
@State var rotation: Angle = .zero
let cube = ModelEntity(mesh: .generateBox(size: 0.25))
var dragGesture: some Gesture {
DragGesture()
.targetedToAnyEntity()
.onChanged { value in
Task { @MainActor in
if value.translation.width < 0 {
rotation.degrees -= 5.0
}
if value.translation.width > 0 {
rotation.degrees += 5.0
}
}
}
}
var body: some View {
RealityView { rvc in
rvc.add(cube)
} update: { rvc in
if let model = rvc.entities.first as? ModelEntity {
model.generateCollisionShapes(recursive: false)
model.components.set(InputTargetComponent())
model.orientation = .init(angle: -Float(rotation.radians),
axis: [0, 0, 1])
}
}.gesture(dragGesture)
}
}