Search code examples
swiftroundingscenekitarkitrealitykit

Rounding positional data from ARKit


I have this code that gets X, Y, Z positions from each frame in ARKit.

let CamPosition = SCNVector3(transform.m41, transform.m42, transform.m43)

How would I round the numbers down because they output occasionally in scientific notation like this?

SCNVector3(x: 7.276927e-09, y: 2.4679738e-09, z: 3.395949e-10)

Instead of the desired output like this:

SCNVector3(x: 0.026048008, y: 0.0069037788, z: 0.010655182)

Any help is greatly appreciated!


Solution

  • Rounding to Meters

    For that you can use three holy methods: round(_:), and ceil(_:), and floor(_:).

    import SceneKit
    import Foundation
    
    let node = SCNNode()
    
    node.position = SCNVector3(x: floor(12.856288),
                               y:  ceil(67.235459),
                               z: round(34.524305))
    
    
    node.position.x    //  12
    node.position.y    //  68   
    node.position.z    //  35
    

    Rounding XYZ values to integer, you make them to translate intermittently (discretely) in meters.


    Rounding to Centimeters

    Rounding XYZ values to 2 decimal places:

    node.position = SCNVector3(x: round(12.856288 * 100) / 100.0,
                               y: round(67.235459 * 100) / 100.0,
                               z: round(34.524305 * 100) / 100.0)
    
    node.position.x    //  12.86   (hundredths)
    node.position.y    //  67.24
    node.position.z    //  34.52