- Home /
Glue GameObject to vertex;
Hello, how can I make object glued to closest point on mesh? Mesh have script what bend it and I need gameobject follow one vertex of mesh. I tried somethink like this but position of object is far away:
public MeshFilter Meh;
Mesh me;
int i;
void Start()
{
float dis = Mathf.Infinity;
me = Meh.mesh;
for(int j=0;j<me.vertexCount; j++)
{
if(Vector3.Distance(transform.TransformPoint(me.vertices[j]),transform.position)<dis)
{
dis = Vector3.Distance(transform.TransformPoint(me.vertices[j]), transform.position);
i = j;
}
}
}
void Update()
{
transform.position =transform.TransformPoint(me.vertices[i]);
}
Answer by Bunny83 · Mar 21, 2019 at 11:13 AM
You have to use the transform of the actual mesh object when you transform it from local to world space. It seems that you want to move the object this script is attached to and the object with the MeshFilter is a different object.
Apart from that your code is extremely inefficient. Each time you access me.vertices
you will create a new copy of the vertices array. Depending on the complexity of the mesh you may allocate several mega bytes of memory. Also to find the closest vertex to a certain point, it's easier to reverse the process. So convert your objects position into localspace of the mesh and work with the local space positions to find out the closest one. Something like that:
public MeshFilter filter;
Mesh me;
int i;
void Start()
{
float dis = Mathf.Infinity;
me = filter.mesh;
// Get the vertices array once
Vector3[] verts = me.vertices;
// this object's position in localspace of the mesh
Vector3 pos = filter.transform.InverseTransformPoint(transform.position);
for(int j = 0;j < verts.Length; j++)
{
// square distance is cheaper for pure comparing
float d = (verts[j] - pos).sqrMagnitude;
if(d < dis)
{
dis = d;
i = j;
}
}
}
void Update()
{
transform.position = filter.transform.TransformPoint(me.vertices[i]);
}
Note that if the mesh doesn't change after the start you may want to just store the local position of the vertex you're interested in. However if the mesh itself is changed at runtime, you have to get a new copy of the vertices array each time. This all of course assumes that the "Mesh" object is actually kept and not replaced each time the mesh is changed.
Thank you, it works! And for lesson, I really didn't know that Each time I access "me.vertices" I will create a new copy of the vertices array.. Now I know how to do this, thank you.
Your answer
Follow this Question
Related Questions
Creating a mesh for an overview map 0 Answers
Mesh.vertices are all 0? 1 Answer
How do I get vertex positions of the referenced game object, and not its mesh? 2 Answers
Why vertex positions appear (0.0, 0.0, 0.0) ? 1 Answer
Using compute shader, how to take every vertex of a mesh and make a cube spawn and move to each one? 0 Answers