How to delete all faces with distance to other object I want to delete all faces (of "Mesh") with a distance > 0.5 to the nearest point of an other object ("Sphere").
Unfortunately it deletes the whole object.

Thanks for helping!



import bpy
import bmesh
from math import sqrt

# Get the active mesh

obj_sphere = bpy.data.objects['Sphere']
obj = bpy.context.edit_object
me = obj.data

# Get a BMesh representation
bm = bmesh.from_edit_mesh(me)

for face in bm.faces:

    # select face and Sphere
    bpy.ops.mesh.select_all(action='TOGGLE')
    face.select = True
    obj_sphere.select = True

    # get distance for selected objects
    l = []
    for item in bpy.context.selected_objects:
        l.append(item.location)

    distance = sqrt( (l[0][0] - l[1][0])**2 + (l[0][1] - l[1][1])**2 + (l[0][2] - l[1][2])**2)

    # check distance &gt; 0.5 and delete
    if distance &gt; 0.5:
        bpy.ops.mesh.delete(type='FACE')

bmesh.update_edit_mesh(me, True)
This code does the trick, and uses some nice built in functions to make things simpler:

import bpy, bmesh

s = bpy.data.objects['Sphere']
o = bpy.context.object

bpy.ops.object.mode_set(  mode   = 'EDIT'     )
bpy.ops.mesh.select_all(  action = 'DESELECT' )
bpy.ops.mesh.select_mode( type   = 'FACE'     )

bm = bmesh.from_edit_mesh( o.data )

for f in bm.faces:
    # Calculate the global location of the current face's median point
    gCenterMedian = o.matrix_world * f.calc_center_median()

    # Find the closest point on the Sphere to the current face's median
    loc = s.closest_point_on_mesh( gCenterMedian )[0]

    # Find the distance by calculating the length of the vector between the two points
    distance = ( loc - gCenterMedian).length

    if distance &lt; 0.5: f.select = True

bm.select_flush( True )

# Delete all selected faces
bpy.ops.mesh.delete( type = 'FACE' )

bpy.ops.object.mode_set( mode = 'OBJECT' )


As the gif shows, reverse the sign to delete far away faces