Thursday, 18 October 2018

Determine if SKNode is in front of camera view (ARKit Spritekit)

I'm trying to detect when the camera is facing my object that I've placed in ARSKView. Here's the code:

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
        guard let sceneView = self.view as? ARSKView else {
            return
        }

        if let currentFrame = sceneView.session.currentFrame {
            //let cameraZ =  currentFrame.camera.transform.columns.3.z
            for anchor in currentFrame.anchors {
                if let spriteNode = sceneView.node(for: anchor), spriteNode.name == "token", intersects(spriteNode) {
                    // token is within the camera view
                    let distance = simd_distance(anchor.transform.columns.3,
                                                 currentFrame.camera.transform.columns.3)
                    //print("DISTANCE BETWEEN CAMERA AND TOKEN: \(distance)")
                    if distance <= captureDistance {
                        // token is within the camera view and within capture distance
                        print("token is within the camera view and within capture distance")
                    }
                }
            }
        }
    }

The problem is that the intersects method is returning true both when the object is directly in front of the camera, as well as directly behind you. How can I update this code so it only detects when the spriteNode is in the current camera viewfinder? I'm using SpriteKit by the way, not SceneKit.

Here's the code I'm using to actually create the anchor:

        self.captureDistance = captureDistance
        guard let sceneView = self.view as? ARSKView else {
            return
        }

        // Create anchor using the camera's current position
        if sceneView.session.currentFrame != nil {

            print("token dropped at \(distance) meters and bearing: \(bearing)")

            // Add a new anchor to the session
            let transform = getTransformGiven(bearing: bearing, distance: distance)
            let anchor = ARAnchor(transform: transform)
            sceneView.session.add(anchor: anchor)
        }

        func getTransformGiven(bearing: Float, distance: Float) -> matrix_float4x4 {
        let origin = MatrixHelper.translate(x: 0, y: 0, z: Float(distance * -1))
        let bearingTransform = MatrixHelper.rotateMatrixAroundY(degrees: bearing * -1, matrix: origin)
        return bearingTransform
    }



from Determine if SKNode is in front of camera view (ARKit Spritekit)

No comments:

Post a Comment