Reg*_*_AG 2 xcode objective-c scenekit swift
我想知道如何获得两个SCNNode(ObjC和Swift)之间的距离
谢谢
简单几何: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)
Run Code Online (Sandbox Code Playgroud)
或使用扩展名和运算符重载:
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)
}
Run Code Online (Sandbox Code Playgroud)
然后:
let distance = node2Pos - node1Pos
let length = distance.length()
Run Code Online (Sandbox Code Playgroud)
斯威夫特 4
SceneKit 中没有内置函数,但 GLKit 有 GLKVector3Distance。尽管如此,在将 SCNVector3 位置转换为 GLKVector3 位置后,您可以将它与 SCNNodes 一起使用,并使用SCNVector3ToGLKVector3。像这样:
let node1Pos = SCNVector3ToGLKVector3(node1.presentation.worldPosition)
let node2Pos = SCNVector3ToGLKVector3(node2.presentation.worldPosition)
let distance = GLKVector3Distance(node1Pos, node2Pos)
Run Code Online (Sandbox Code Playgroud)
最有效的方法是使用 simd。
extension SCNVector3 {
func distance(to vector: SCNVector3) -> Float {
return simd_distance(simd_float3(self), simd_float3(vector))
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
node1.position.distance(to: node2.position)
Run Code Online (Sandbox Code Playgroud)
~ 0.00001 秒
| 归档时间: |
|
| 查看次数: |
2900 次 |
| 最近记录: |