I am trying to script some object manipulation using the bmesh module.

During steps of this scripting I would like to be able to use the closest_point_on_mesh function. However I get unexpected results.

A minimal working example looks like this:

import bpy
import bmesh
from mathutils import Vector



obj = bpy.context.active_object

bm = bmesh.new()

# do some stuff to the bmesh


# get a face for testing
face = bm.faces[0]

# getting the "middle" of the face
xyz = Vector((0,0,0))
for v in face.verts:
  xyz += v.co/3

# the middle of the face

location,normal,index = obj.closest_point_on_mesh(xyz)

# prints 0,0,0. expected the same as xyz three lines above

I expect the value of location to be the same as (or close to) the value of xyz, but it prints 0,0,0.

What am I doing wrong? Is there a better way of doing this?

  • $\begingroup$ For anyone who stumbles upon this in the future: I think the error was related to me getting local and global coordinates mixed up somehow. I don't have the time to re-test this right now, but I figured I should give a heads-up just in case. $\endgroup$ – inconvergent Jan 26 '15 at 14:13
  • 1
    $\begingroup$ this code seems to be running as expected after adding bm.faces.ensure_lookup_table() also it's easier to use face.calc_center_median() to get the center $\endgroup$ – Chebhou Apr 1 '15 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.