首页 > 解决方案 > RealityKit – 平面检测

问题描述

在与 ARKit 类似的 RealityKit 中,物体在相机检测到某种平面之前不会显示。一旦相机检测到该表面,对象将显示并固定在该表面上。

我如何(通过代码)知道相机是否检测到平面?实际上,我想突出显示可选区域,但我不确定 RealityKit 是否真的允许你这样做,我知道 SceneKit 可以。

标签: swiftaugmented-realityarkitrealitykit

解决方案


planeRealityKit 中有一个用于此目的的初始化程序(和枚举案例):

convenience init(plane alignment: AnchoringComponent.Target.Alignment,
                  classification: AnchoringComponent.Target.Classification, 
                   minimumBounds: SIMD2<Float>) 

/* Where `minimumBounds` is the minimum size of the target plane */

它是 ARKit 的ARPlaneAnchorwithextent属性的对应物(即检测到的平面的估计宽度和长度)。但在 RealityKit 中,它的工作方式有点不同。

在实际代码中,您可以这样使用它:

let anchor = AnchorEntity(.plane([.horizontal, .vertical],
                 classification: [.wall, .table, .floor],
                  minimumBounds: [0.375, 0.375]))

/* Here we create an anchor for detected planes with a minimum area of 37.5 cm2 */

anchor.addChild(semiTranparentPlaneEntity)        // visualising a detected plane
arView.scene.anchors.append(anchor)

请注意,alignment参数classification符合 OptionSet 协议。

并且您总是可以找出平面锚是否已创建:

let arView = ARView(frame: .zero)

let anchor = AnchorEntity(.plane(.any, classification: .any, 
                                        minimumBounds: [0.5, 0.5]))
anchor.name = "PlaneAnchor"


let containsOrNot = arView.scene.anchors.contains(where: {
    $0.name == "PlaneAnchor"
})
print(containsOrNot)

print(arView.scene.anchors.count)
print(arView.scene.anchors.first?.anchor?.id)

推荐阅读