Help trying to find nearest vertex on mouse click

I’m trying to find a simple way to write a script that would find the nearest vertex to the mouse cursor in the 3D view when a mouse button is clicked, but am not sure where to start. I was thinking one of the bpy_extras.view3d_utils methods like region_2d_to_vector_3d, region_2d_to_location_3d, location_3d_to_region_2d, but haven’t had any success.

My pseudo code was along the lines of this:

If LEFTMOUSE click detected:Search within N distance of cursor location for vertex
if a vertex is found:
[INDENT=2]return vertex location and name of object vertex is attached to

[/INDENT]
EDIT: Corrected a mistake (underlined), meant closest vertices to the mouse cursor as they appears on the 3D view, not via Blender units.

Have you seen this?

I saw it, but I never was able to make the example script run. Blender will load t, but the bl_label “Simple Object Operator” does not show up in the Space Bar Menu.

Did you try it in edit mode? it requires that.

Huh, I was sure I tried that, but apparently I did not because now it works. Thanks for the suggestion.

Hmm… You wouldn’t happen to know of anything similar for object mode? I had no luck searching through Blender’s Python interface and I’m not familiar enough with the Blender API to convert the program myself. The KDTrees suggestion in that link should be workable though. I might hack some abomination together using the KDTree Utilities and a bunch of for loops as a workaround for now.

So I tried converting the mouse position to 3D coordinates (via region_2d_to_location_3d and region_2d_to_vector_3d) and using KDTree to find the closest vertex to the mouse cursor, but that gave me some undesired results due to the arbitrary Z coordinate the mouse location is being assigned.

As a second option I tried converting everything to 2D coordinates with location_3d_to_region_2d, but that is also giving me undesired results. I’m not sure what is causing the problem doing this in 2D.

I’ve embedded both rough draft scripts into the “.blend” file below (I can attach the scripts seperately if needed). I used OpenGL to highlight the vertices my script is interpretting as “closest” the mouse cursor.

Any info on how to prevent vertices nowhere near the mouse cursor from being highlighted?

getClosVert.blend (708 KB)