RealityKit – Which Entity is intersecting with other Entity

Viewed 289
let height: Float = 1
let width: Float = 0.5
let box = MeshResource.generateBox(width: 0.02, height: height, depth: width)

This box will have a real-time position same as the current camera position, In AR World I would have multiple boxes with different shapes, I want to identify which object is intersecting with the current real-time box.

I can not do this with position matching (The nearest one). I literally want to know the object which is touching/intersecting the real-time box.

Thanks in advance.

1 Answers

You can easily do that using subscribe() method. The following code is a reference:

(physics for both objects was enabled in Reality Composer)

import UIKit
import RealityKit
import Combine

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    var subscriptions: [Cancellable] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let boxScene = try! Experience.loadBox()
        arView.scene.anchors.append(boxScene)
        
        let floorEntity = boxScene.children[0].children[1]

        let subscribe = arView.scene.subscribe(to: CollisionEvents.Began.self,
                                               on: floorEntity) { (event) in
            print("Collision Occured")
            print(event.entityA.name)
            print(event.entityB.name)
        }
        
        self.subscriptions += [subscribe]
    }
}

enter image description here

Related