Move vertices to nearest neighbors

Let us know if you have a nice R.U.B.E script to share!
Post Reply
iforce2d
Site Admin
Posts: 861
Joined: Sat Dec 22, 2012 7:20 pm

Move vertices to nearest neighbors

Post by iforce2d »

This script will move all selected vertices to the position of their nearest un-selected neighbor vertex.

Code: Select all

//change as necessary
float maxSnapRange = 1;
bool allowSnappingToVertexOfSameFixture = true;

vertex[] svs = sv();
vertex[] avs = av();

array<vertex> newPoints;
array<vec2> newPointPositions;

for (uint i = 0; i < svs.length; i++) {
	vertex v = svs[i];
	vertex closest;
	float closestDist = 999999;
	for (uint k = 0; k < avs.length; k++) {
		vertex other = avs[k];
		if ( v == other )
			continue;
		if ( other.isSelected() )
			continue;
		if ( other == v.next() || other == v.prev() )
			continue;
		if ( ! allowSnappingToVertexOfSameFixture && v.getFixture() == other.getFixture() )
			continue;
		float dist = v.wpos.distanceTo( other.wpos );
		if ( dist > maxSnapRange )
			continue;
		if ( dist < closestDist ) {
			closest = other;
			closestDist = dist;
		}
	}
	if ( closestDist != 999999 ){
		newPoints.insertLast( v );
		newPointPositions.insertLast( closest.wpos );
	}
}

for (uint i = 0; i < newPoints.length; i++) {
	vertex v = newPoints[i];
	vec2 wpos = newPointPositions[i];
	v.setWorldPos( wpos );
}
Examples, before and after:
snapClosestVertex1.png
snapClosestVertex1.png (14.85 KiB) Viewed 48027 times
snapClosestVertex2.png
snapClosestVertex2.png (14.7 KiB) Viewed 48027 times
The script is mainly meant as a convenience to avoid excessive clicking and menu accessing, because normally this operation would need to be done one vertex at a time, setting the cursor at the target position and then aligning to it. There is no clever checking for invalid cases - you will need to have a clear intention of which vertices should go where and select them sensibly to prevent cases like this:
snapClosestVertex3.png
snapClosestVertex3.png (13.27 KiB) Viewed 48027 times
Post Reply