
Snapping an empty to the closest vertex of a cube. "Closest" meaning closest to the viewer.
First, loop through the areas or obtain a SpaceView3D by other means. The type of this area returns VIEW_3D. It's first space will be a VIEW_3D space. This space has a region_3d property, which has a perspective_matrix property.
The perspective_matrix appears to be the perspective view transform matrix. Mutliple a 3D Vector by the matrix, to get its position relativ to the camera.
Here is a working sample.
import bpy
# function returning the closest vertex of
# param 'ob' is an object in the scene with vertices
def get_closest_vertex_position(scene, ob):
# get an area of type VIEW_3D
areas = [a for a in bpy.context.screen.areas if a.type == 'VIEW_3D']
if not len(areas):
return
region3d = areas[0].spaces[0].region_3d
# get the view matrix
view_mat_inv = region3d.view_matrix
if region3d.is_perspective:
vertices = [[v, (view_mat_inv*v.co).length] for v in ob.data.vertices]
else:
vertices = [[v, -(view_mat_inv*v.co).z] for v in ob.data.vertices]
# use a lamda expression to get closest vertex
return min(vertices, key = lambda x: x[1])[0].co
view_matrixin the descriptive paragraphs? – Robin Betts Jul 15 '19 at 13:05perspective_matrix,window_matrixandview_matrix. The code works viewperspective_matrix, although I don't know why. If you could clarify, that would be great. – Leander Jul 15 '19 at 13:12view_matrixis the xform from world space to viewpoint space (the inverse of the world xform of the viewpoint).. whatwindow_matrixis depends on whether your view is orthogonal or perspective, and in either case gives the xform from the current window-shaped frustum to a canonical view volume, a cube -1 to 1 in X,Y and Z, viewpoint at 0. Theperspective_matrixgives the 1st xform followed by the 2nd. – Robin Betts Jul 16 '19 at 15:57