S01E16:点与球体的距离

609 阅读1分钟

说明

三维中,点与球体位置关系有:点在球体内部,点在球面上,点在球体内部。用点到球心的距离,与球体半径比较就可以表示这三种关系。

几何

如图,球心为点 A,点 B 为球体表面上一点,点 C 为球体外部一点,点 D 为球体内部一点:

我们知道,计算距离是需要开方的,没有必要的话,尽量用长度或距离的平方来表示,所以如果只是想知道点在不在球体内部,则不需要计算距离,只需要距离平方就行了。

代码

static func distanceBetween(point:simd_float3, sphere:Sphere) -> Float {
    let distanceCenter = distance(point, sphere.position)
    return distanceCenter - sphere.radius
}

static func isPointInsideSphere(point:simd_float3, sphere:Sphere) -> Bool {
    return distance_squared(sphere.position, point) < sphere.radius * sphere.radius
}
static func isPointOnSphere(point:simd_float3, sphere:Sphere) -> Bool {
    return abs(distance_squared(sphere.position, point) - sphere.radius * sphere.radius) < 0.000001
}