VisionOS - 使用锚点设置实体位置

问题描述 投票:0回答:1

我正在开发 VisionOS 应用程序,但我有点坚持将实体放置在沉浸式空间中。

我想要什么:

  1. 用户输入
    ImmersiveSpace
  2. 他们面前出现一个球体(在他们的视野中,在头部高度)
  3. 然后他们可以使用
    DragGesture()
  4. 移动球体

我遇到的问题是手势和位置似乎不能很好地配合。我可以正确定位球体,但是当拖动它时,它会在视图中跳跃。就好像原来的位置又加了一次,让它跳跃了

这是我到目前为止的代码:

//  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!
                    )
                }
        )
    }
}

swiftui realitykit visionos
1个回答
0
投票

您需要一个中间属性来存储模型在 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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.