How to achieve dynamic scaling based on distance in ARKit

Viewed 297

I have a simple SCNNode that is placed in a real-world position, the node corresponds to a landmark with known coordinates. In terms of the user, I want the SCNNode to have the same size despite the distance changing between the location of the node and the user/ARcamera. Here is my code so far, it is a very crude way to calculate the scale based on the distance.

func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
    self.updateScaleOfNodes(node: nodeAdded, fromPointOfView: self.sceneView.pointOfView!)
}

func updateScaleOfNodes(node: SCNNode, fromPointOfView pointofView: SCNNode){

    //Find the 3D objects position
    let nodePosition = SCNVector3ToGLKVector3(node.worldPosition)

    //Find the cameras current position
    let currentCameraPosition = SCNVector3ToGLKVector3(pointofView.worldPosition)

    //Find the distance between camera and 3D object
    let distanceBetweenCameraAndNode = GLKVector3Distance(nodePosition, currentCameraPosition)
    self.locationAcc.isHidden = false
    let distance_test = "Distance between camera and node:" + String(distanceBetweenCameraAndNode)
    self.locationAcc.text = distance_test
    //180 metres

    //NOTE: Do not calculate delta distance between node and current position because that focuses on the size of each step rather than how far away your current position is from the node

    //Begin animation
    SCNTransaction.begin()
    SCNTransaction.animationDuration = 0.3

    //Multiply distance by scaling factor
    //Each metre you walk away the node scales down by 1cm
    let scale:Float = 1/1000 * distanceBetweenCameraAndNode

    //Calculate the scale difference (moving closer will make node larger)
    let scaleDiff:Float = 1 - scale

    //Assign the scale to 3D object
    node.scale = SCNVector3(scaleDiff * Float(scale_W), scaleDiff * Float(scale_H), scaleDiff * Float(scale_l))

    SCNTransaction.commit()
}

When I have tested this code, I have found some objects tend to work well where others do not. Is there a better solution that can be applied to all objects of different dimensions? I have looked into a solution using the field of view, but I'm not really sure if it is a better solution than this. Any recommendations and advice would be greatly appreciated.

Thanks in advance

0 Answers
Related