'SceneKit : how to get distance between two SCNNode ? (ObjC and Swift)

I wonder how to get distance between two SCNNode (ObjC and Swift)

Thanks



Solution 1:[1]

The most efficient way is to use simd.

 extension SCNVector3 {
     func distance(to vector: SCNVector3) -> Float {
         return simd_distance(simd_float3(self), simd_float3(vector))
     }
 }

Usage:

node1.position.distance(to: node2.position)

~ 0.00001 sec

Solution 2:[2]

Simple geometry :P

Swift 3:

let node1Pos = node1.presentation.worldPosition
let node2Pos = node2.presentation.worldPosition
let distance = SCNVector3(
    node2Pos.x - node1Pos.x,
    node2Pos.y - node1Pos.y,
    node2Pos.z - node1Pos.z
)
let length: Float = sqrtf(distance.x * distance.x + distance.y * distance.y + distance.z * distance.z)

Or use extension and operator overload:

extension SCNVector3 {
    func length() -> Float {
        return sqrtf(x * x + y * y + z * z)
    }
}
func - (l: SCNVector3, r: SCNVector3) -> SCNVector3 {
    return SCNVector3Make(l.x - r.x, l.y - r.y, l.z - r.z)
}

Then:

let distance = node2Pos - node1Pos
let length = distance.length()

Solution 3:[3]

Swift 4

There's no built-in function in SceneKit, but GLKit has GLKVector3Distance. Still, you can use it with SCNNodes, after converting the SCNVector3 positions to GLKVector3 positions, with SCNVector3ToGLKVector3. Like this:

let node1Pos = SCNVector3ToGLKVector3(node1.presentation.worldPosition)
let node2Pos = SCNVector3ToGLKVector3(node2.presentation.worldPosition)

let distance = GLKVector3Distance(node1Pos, node2Pos)

Solution 4:[4]

import SceneKit

extension SCNVector3 {

// All three distance methods return the same value.

func distance(to: SCNVector3) -> Float {
    let distance = SCNVector3(
        x - to.x,
        y - to.y,
        z - to.z
    )
    return sqrtf(distance.x * distance.x + distance.y * distance.y + distance.z * distance.z)
}

func simdDistance(to vector: SCNVector3) -> Float {
    return simd_distance(simd_float3(self), simd_float3(vector))
}

func glk3DDistance(to vector: SCNVector3) -> Float {
    let vectorSelf = SCNVector3ToGLKVector3(self)
    let compareVector = SCNVector3ToGLKVector3(vector)
    return GLKVector3Distance(vectorSelf, compareVector)
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ???? ???????
Solution 2
Solution 3 drewster
Solution 4 Darkwonder