首页 > 解决方案 > 如何让 RealityKit 只显示 CollisionComponents?

问题描述

我试图在我的 ARView 上查看 CollisionComponents。

我将其.showPhysics用作 debugOptions 的一部分,但由于屏幕上有 20 个对象,我让所有法线都变得疯狂,并且 CollisionComponents 的颜色不清楚(某种形式的奇怪粉红色)。

有谁知道如何只呈现 CollisionComponents 而没有任何额外数据作为.showPhysics?

标签: swiftaugmented-realityarkitrealitykit

解决方案


您可以使用简单的 Swift 扩展来扩展 RealityKit 的 ARView 的标准功能:

import RealityKit
import ARKit

fileprivate extension ARView.DebugOptions {

    func showCollisions() -> ModelEntity {

        print("Code for visualizing collision objects goes here...")

        let vc = ViewController()

        let box = MeshResource.generateBox(size: 0.04)    
        let color = UIColor(white: 1.0, alpha: 0.15)    
        let colliderMaterial = UnlitMaterial(color: color)

        vc.visualCollider = ModelEntity(mesh: box,
                                   materials: [colliderMaterial])    
        return vc.visualCollider
    }
}

...然后在您点击屏幕时在 ViewController 中调用此方法:

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    let anchor = AnchorEntity()
    var ballEntity = ModelEntity()
    var visualCollider = ModelEntity()
    var sphere: MeshResource?

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {

        sphere = MeshResource.generateSphere(radius: 0.02)

        let material = SimpleMaterial(color: .systemPink,
                                 isMetallic: false)

        ballEntity = ModelEntity(mesh: sphere!,
                            materials: [material])

        let point: CGPoint = sender.location(in: arView)

        guard let query = arView.makeRaycastQuery(from: point,
                                              allowing: .estimatedPlane,
                                             alignment: .any)
        else { return }

        let result = arView.session.raycast(query)

        guard let raycastResult = result.first
        else { return }

        let anchor = AnchorEntity(raycastResult: raycastResult)
        anchor.addChild(ballEntity)
        arView.scene.anchors.append(anchor)

        let showCollisions = arView.debugOptions.showCollisions()  // here it is
        ballEntity.addChild(showCollisions)

        ballEntity.generateCollisionShapes(recursive: true)
    }
}

请考虑,这是一个近似的可视化。这段代码只是向您展示了一种继续前进的方式。

在此处输入图像描述


推荐阅读