0
$\begingroup$

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


bpy.ops.mesh.primitive_ico_sphere_add(
  subdivisions=1,
  size=1,
  location=(0,0,0))

bpy.ops.object.select_pattern(pattern='Icosphere')

obj = bpy.context.active_object
bpy.ops.object.mode_set(mode='EDIT')

bm = bmesh.new()
bm.from_mesh(obj.data)

# do some stuff to the bmesh

bpy.ops.object.mode_set(mode='OBJECT')
bm.to_mesh(obj.data)

# 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
print(xyz,'xyz')

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

# prints 0,0,0. expected the same as xyz three lines above
print(location,'location')

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?

$\endgroup$
  • $\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.