Search code examples
swiftscenekitvirtual-realityraycastingrealitykit

SceneKit- Cannot query using bitmask


We were able to have custom raycasting using bitmasks:

let hitTest = sceneView.hitTest(location, options: [categoryBitMask: bitmask])

But hitTest is deprecated now and I can't figure out how to set bitmask for raycast query:

let query = sceneView.raycastQuery(from: location, allowing: .estimatedPlane, alignment: .horizontal)

Solution

  • SceneKit

    In SceneKit you can use bitmasks in context of [SCNHitTestResult]. hitTest(_:options:) instance method is not deprecated yet and it works in iOS 15.4.

    let sceneView = ARSCNView(frame: .zero)
    
    enum HitTestType: Int {
        case object_A = 0b00000001
        case object_B = 0b00000010
    }
    
    let point: CGPoint = gesture.location(in: self.sceneView)
    
    let bitMask = HitTestType.object_A.rawValue | HitTestType.object_B.rawValue
    
    let results = sceneView.hitTest(point, options: [.categoryBitMask: bitMask])
    

    P.S.

    Only hitTest(_:types:) is deprecated at the moment.


    RealityKit

    In RealityKit you can use bitmasks in CollisionCastHit's context:

    let arView = ARView(frame: .zero)
    
    let point: CGPoint = gesture.location(in: self.arView)
        
    let (origin, direction) = arView.ray(through: point)!
        
    let raycasts: [CollisionCastHit] = arView.scene.raycast(origin: origin, 
                                                         direction: direction, 
                                                            length: 50, 
                                                             query: .any, 
                                                              mask: .default, 
                                                        relativeTo: nil)
    

    ...or this way:

    let raycasts: [CollisionCastHit]  = arView.hitTest(point, 
                                                       query: .any, 
                                                        mask: .default)