instructions

There are two kinds of positions of two spheres: intersecting and disintersecting. When intersecting, one sphere may completely contain the other sphere.

The geometric

It’s easy to figure out the position relationship by calculating the distance from the center of the sphere and comparing it with the radius. For computational efficiency, you can also use distance squared, radius squared.The spheres intersect when the square of the distance between the center of the sphere is less than the square of the sum of the radii; Otherwise it’s disjoint.

However, it should also be noted that inclusion occurs when the square of the distance between the center of the sphere is less than the square of the difference between the radii. If we need common points on the surface of the sphere, they don’t exist in this case. In other words, when the spheres intersect, there’s volume intersection and surface intersection.

code

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// It doesn't matter, we just need the square value
    
    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// It doesn't matter, we just need the square value
    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
}

Copy the code