# Detect objects that are touching

how one can detect two object contact. with python, for example, I want every sphere becomes the child of the cube it touches.

Using closest point on mesh

Test code, assumes spheres are named "Sphere[.nnn]" and cubes "Cube[.nnn]" If a hit from the sphere's centre to a point on a cube is less than the sphere's radius, then it parents them.

import bpy
from bpy import context

scene = context.scene
spheres = [o for o in scene.objects if o.name.startswith("Sphere")]
cubes = [o for o in scene.objects if o.name.startswith("Cube")]

for s in spheres:
o = s.matrix_world.to_translation()
for cube in cubes:
cmwi = cube.matrix_world.inverted()
local_pos = cmwi * o
(hit, loc, norm, face_index) = cube.closest_point_on_mesh(local_pos)
if hit:
v2 = cube.matrix_world * loc
# distance from global hit to cube
l = (v2 - o).length

• Change to (loc, norm, face_index) = cube.closest_point_on_mesh(local_pos) and just fudge in hit = True ... or better still upgrade. – batFINGER Sep 20 '16 at 15:14