在 Vision OS 中查找 3D 模型的尺寸

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

我知道 3D 模型的变换提供了缩放、旋转和平移信息,但是我们有没有办法在 Vision OS 中计算 3D 模型的大小?

swiftui 3d size visionos
1个回答
0
投票

在visionOS中获取模型尺寸

在 RealityKit 中,有 2 种方法可以了解模型的尺寸。第一种方法可以在这里找到。第二个更方便,因为您只需点击模型,

raycast(..)
方法就会返回所需的值。

import SwiftUI
import RealityKit

struct ContentView : View {        
    @State var sizeOfModel: String = ""
    var material = UnlitMaterial()
    let building = ModelEntity(mesh: .generateBox(width: 1.0,
                                                 height: 3.5,
                                                  depth: 1.0))
    init() {
        material.color.texture = .init(try! .load(named: "texture"))
        building.model?.materials = [material]
    }
    
    var body: some View {
        RealityView { realityViewContent in
            building.components.set(InputTargetComponent())
            building.generateCollisionShapes(recursive: false)
            
            let offset = building.visualBounds(relativeTo: nil).extents.y / 2
            building.position.y += offset
            building.position.z = -5.0
            realityViewContent.add(building)
        }
        .gesture(
            TapGesture()
                .targetedToAnyEntity()
                .onEnded { tapValue in
                    let scene = tapValue.entity.scene!
                                        
                    guard let castHit = scene.raycast(from: [0, 2, 10],
                                                        to: [0, 2,-10]).first
                    else { return }
                    
                    let size = castHit.entity.visualBounds(relativeTo: nil)
                    let x = size.extents.x
                    let y = size.extents.y
                    let z = size.extents.z
                    
                    sizeOfModel = "Building's size is: \(x)m X \(y)m X \(z)m"
                    print(sizeOfModel)
                }
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.