SceneKit:如何获得两个SCNNode之间的距离? (ObjC和Swift)

时间:2017-09-06 17:27:58

标签: objective-c swift xcode scenekit

我想知道如何在两个SCNNode(ObjC和Swift)之间找到距离

由于

3 个答案:

答案 0 :(得分:5)

简单几何:P

斯威夫特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)

或者使用扩展和运算符重载:

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)
}

然后:

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

答案 1 :(得分:4)

Swift 4

SceneKit中没有内置函数,但GLKit有 的 GLKVector3Distance 即可。在使用 SCNVector3ToGLKVector3 将SCNVector3位置转换为GLKVector3位置后,您可以将其与SCNNodes一起使用。像这样:

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

let distance = GLKVector3Distance(node1Pos, node2Pos)

答案 2 :(得分:1)

最有效的方法是使用simd。

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

用法:

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

〜0.00001秒