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*);*
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*);*
} 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.