- Home /
Procedural Vertex Snapping
I'm wondering if there is a way to perform Vertex to Vertex snapping within a script (procedurally). I know theres one in-built in the Unity3 Editor, but I need to generate/instantiate my levels dynamically on load. Essentially I have a bunch of track pieces that I want to piece together in a randomized fashion, getting a different track each time.
Are there any scripts out there for something like this? Or is it something I'd have to script by manipulating each objects mesh, making the vertices of the two objects meet?
Cheers
Answer by Statement · Dec 15, 2010 at 01:58 AM
I propose a simple method that doesn't manipulate meshes at all.
- It requires your meshes already to be modeled in a manner that allows track blocks to be placed adjacently without having to edit vertices.
For every track (block) you have, you can add a number of empty game objects with a unique tag, such as "snap point" to indicate that another block can be placed there - extending the track. Each block should have a common origo or root node that will place the track model perfectly for every track part you have if they have the same world matrix. Then it's a simple matter of placing the next block exactly on the position, rotation and scale of the nearest snap transform. Doing so will allow you to build complex tracks effortlessly.
Some caveats to consider is that you should check the nearest snap transform if it is child of the transform you're currently moving, so you don't try to snap onto the new track you're placing.
This method require that all tracks have a similar start and end structure, but can vary in direction, length and can even have forked tracks.
You must naturally flag if a snap point already is occupied with another track so you can't place two tracks on the same snap point.
I hope this helps. Think simple. :)
I have created some waypoints for the track, and your solution works great. Except that using the code: path.transform.position = snapFront.position; Gets me into a pickle, where obviously the path's center shouldnt be the next snap point, but the snapFront and snapBack should be in the same position. How could I set the position of the path so these two points meet?
It sounds like you have a setup where the "path" has a child called snapBack, and snapBack should snap to location of snapFront? path.transform.position = snapFront.position - snapBack.transform.localPosition;