finding closet face to another object

hi

I am trying to find the closet face to another object with python script. I ran into one problems:

  1. the face was not selected.
    here is my code:

import bpy
import subprocess
import mathutils

find closest face of ob1 to ob2

def closest_face(ob1,ob2):
d=9999999999999.9
f=0
for f1 in ob1.data.polygons:
p1=ob1.matrix_worldf1.center
for f2 in ob2.data.polygons:
p2=ob2.matrix_world
f2.center
p=p1-p2
if (p.xp.x+p.yp.y+p.zp.z) < d:
f=f1
d=(p.x
p.x+p.yp.y+p.zp.z)
return f

def test():
ob1=bpy.data.objects[‘Torus’]
ob2=bpy.data.objects[‘Sphere’]
f=closest_face(ob1,ob2)
bpy.ops.object.mode_set(mode = ‘EDIT’)
bpy.context.tool_settings.mesh_select_mode = [False, False, True]
bpy.ops.mesh.select_all(action = ‘DESELECT’)
f.select=True
ob1.data.polygons.active=f.index

test()

Try this function:

http://www.blender.org/api/blender_python_api_2_73_release/bpy.types.Object.html?highlight=closest#bpy.types.Object.closest_point_on_mesh

It returns a face index.

If you don’t know the target object (i.e. you want find the closest face of any nearby object), use Scene.ray_cast().

To select a face in the standard API, you must be in object mode. If you want to avoid mode switching, consider using the bmesh module. But better test if face indices match up.

Thanks for replying.

Did you ever find a usable solution for this? I need this as well and I wonder if you can share your findings.

.select() is somewhat broken, you should use bmesh module instead to select and deselect individual faces.