1
$\begingroup$

Would it be possible to use the KDTree without taking into account the z-coordinate? According to the documentation, find(co) necessarily requires a vector (x,y,z) but what interests me is to find the nearest point in (x,y) without taking into account the z (which may really vary my result)

$\endgroup$

1 Answer 1

2
$\begingroup$

Arbitrarily set z

Using the example from https://docs.blender.org/api/master/mathutils.kdtree.html#module-mathutils.kdtree

Test script, find all verts within 1 local blender unit in mesh projected to z = 0 plane, from the 3d cursor projected to same plane. Adjust z to suit.

import mathutils

# set the z of the xyplane
z = 0
# create a kd-tree from a mesh
from bpy import context
obj = context.object
mesh = obj.data
size = len(mesh.vertices)
kd = mathutils.kdtree.KDTree(size)

for v in mesh.vertices:
    kd.insert((v.co.x, v.co.y, z), v.index)

kd.balance()


# 3d cursor relative to the object data
co_find = context.scene.cursor.location @ obj.matrix_world.inverted()
# set the same to find nearest projected to that plane.
co_find.z = z 

for co, index, dist in kd.find_range(co_find, 1):
    print(f"Vert[{index}].co[:] = {mesh.vertices[index].co} (xy dist = {dist})")

enter image description here

Test run cursor location in image, selects the vertices of leading edge of cube as seen from camera in default scene.

Vert[1].co = (1.0, -1.0, -1.0) (xy dist = 0.030091779306530952)
Vert[5].co = (0.9999993443489075, -1.0000005960464478, 1.0) (xy dist = 0.030092377215623856)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .