我正在开发 VisionOS 应用程序,但我有点坚持将实体放置在沉浸式空间中。
我想要什么:
ImmersiveSpace
DragGesture()
我遇到的问题是手势和位置似乎不能很好地配合。我可以正确定位球体,但是当拖动它时,它会在视图中跳跃。就好像原来的位置又加了一次,让它跳跃了
这是我到目前为止的代码:
// ImmersiveView.swift
import SwiftUI
import RealityKit
import RealityKitContent
struct ImmersiveView: View {
@State private var entity = Entity()
var body: some View {
RealityView {
content in
do {
entity = try await Entity(named: "Sphere", in: realityKitContentBundle)
let anchor = AnchorEntity(.head)
anchor.anchoring.trackingMode = .once
entity.setParent(anchor)
content.add(anchor)
entity.position = SIMD3<Float>(0, 0, -1)
entity.name = "Head Anchor"
} catch {
print("Error loading Sphere model: \(error.localizedDescription)")
}
}
.gesture(
DragGesture()
.targetedToEntity(entity)
.onChanged { value in
(entity).position = value.convert(
value.location3D,
from: .local,
to: (entity).parent!
)
}
)
}
}
您需要一个中间属性来存储模型在 3D 空间中的平移值。这是代码
import SwiftUI
import RealityKit
import RealityKitContent
struct ContentView: View {
@State var sphere = Entity()
@State var translation: Vector3D = .zero
let anchor = AnchorEntity(.head, trackingMode: .once)
var gesture: some Gesture {
DragGesture()
.targetedToEntity(sphere)
.onChanged {
$0.entity.position = $0.convert(
$0.translation3D + translation,
from: .local,
to: sphere)
}
.onEnded {
translation += $0.translation3D
}
}
var body: some View {
RealityView { content in
sphere = try! await Entity(named: "Scene", in: rkcb)
sphere.scale *= 5
sphere.position = [0, 0,-4]
anchor.addChild(sphere)
content.add(anchor)
}
.gesture(gesture)
}
}