说明
两个球体的位置有相交和不相交两种,其中相交时,可能会出现一个球体完全包含另一个球体的情况。
几何
判断位置关系很简单,计算球心距离,再和半径比较就可以了。出于计算效率考虑,也可以使用距离的平方,半径的平方。 当球心距离的平方,小于半径之和的平方时,球体就是相交的;否则就是不相交的。
但是,还要注意的是,当球心距离的平方,小于半径之差的平方时,球体会出现包含关系。如果我们需要的是球体表面的公共点,在这种情况下是不存在的。也就是说球体相交时,有体积相交和表面相交的情况。
代码
static func isVolumeIntersection(sphere1:Sphere, sphere2:Sphere) -> Bool {
let radiusFar = sphere1.radius + sphere2.radius
return distance_squared(sphere1.position, sphere2.position) <= radiusFar * radiusFar
}
static func isSurfaceIntersection(sphere1:Sphere, sphere2:Sphere) -> Bool {
let radiusFar = sphere1.radius + sphere2.radius
let radiusNear = sphere1.radius - sphere2.radius//正负无所谓,后面只需要平方值
let distanceSquared = distance_squared(sphere1.position, sphere2.position)
return (distanceSquared <= radiusFar * radiusFar) && (distanceSquared >= radiusNear * radiusNear)
}
static func isContain(sphere1:Sphere, sphere2:Sphere) -> Bool {
let radiusNear = sphere1.radius - sphere2.radius//正负无所谓,后面只需要平方值
let distanceSquared = distance_squared(sphere1.position, sphere2.position)
return distanceSquared <= radiusNear * radiusNear
}
static func isSame(sphere1:Sphere, sphere2:Sphere) -> Bool {
if distance_squared(sphere1.position, sphere2.position) < 0.00001 && abs(sphere1.radius - sphere2.radius) <= 0.00001 {
return true
}
return false
}