# Test if empty touches mesh/depth object with python

I'm doing motion capturing of facial expressions, having an empty (constrained to a track in the movie clip editor) "sliding" on a facial surface mesh (depth object). However, for some large facial movements, the empty "drops off" the depth object. I don't want to enlarge the depth object.

Here the empty "slides" on the depth object (facial mesh):

Here the empty can not be projected on the depth object and "falls off" to some standard distance:

Is there a way to test for each frame whether the empty "touches" the mesh/depth object (or not) in bpy?

• Hard to understand your question. Can you add a scene or some images to show what you are trying to accomplish? – brockmann Jan 17 '18 at 15:18
• Sorry for beeing imprecise. I added some screen shots. – emil Jan 17 '18 at 15:53
• Could use distance from empty to its Closest point on mesh in a frame change handler or somesuch. – batFINGER Jan 17 '18 at 16:07

Thanks to the link of batFINGER to the function closest_point_on_mesh() I wrote a function which does the trick:

def is_empty_on_mesh (empty,mesh,maxDist = .000001):

empty = bpy.data.objects[empty]
mesh = bpy.data.objects[mesh]

# to compute distance via closest_point_on_mesh() the
# objects have to be translated from global to local space
emw = empty.matrix_world.to_translation()
mmwi = mesh.matrix_world.inverted()

local_pos = mmwi * emw
(hit, loc, norm, face_index) = mesh.closest_point_on_mesh(local_pos)
vec = mesh.matrix_world * loc

dist = (vec - emw).length
#print("Function Dist:",dist) # Debugging
return(dist < maxDist)

is_empty_on_mesh(NameOfEmpty, NameOfMesh)


The function returns TRUE or FALSE, depending on the distance being smaller than .000001 (this value is somehow arbitrary).