- Home /
Getting the world position of mesh vertices?
I have some simple mesh objects in my scene, and I want to obtain the position of each vertex in them. So far, I have the following code to do so.
MeshFilter mf = cube.GetComponent<MeshFilter>();
for (int i = 0; i < mf.mesh.vertices.length; i++)
{
Vector3 v = mf.mesh.vertices[i];
...
The problem is that this only obtains the local position of each vertex according to the unmodified mesh. (i.e., cubes will have vertices at (0.5, 0.5, 0.5), (-0.5, 0.5, 0.5), (-0.5, -0.5, 0.5) etc... no matter where the cube is in the scene.)
Is there any way to obtain the world position of these vertices instead of this useless local position?
Answer by IgorAherne · Jan 27, 2017 at 10:16 AM
Don't be so harsh, they are not useless )
Matrix 4x4 localToWorld = transform.localToWorldMatrix;
for(int i = 0; i<mf.mesh.vertices.Length; ++i){
Vector3 world_v = localToWorld.MultiplyPoint3x4(mf.mesh.vertices[i]);
}
More about matrices here
you sir, just saved my life! I was going crazy trying to spawn things at vertices positions, now I can do it! Really really appreciate you sharing your knowledge :D
Answer by robert878 · May 29, 2018 at 04:07 PM
Or use Vector3 worldPt = transform.TransformPoint(meshVert);
Actually not worked like the comment which is voted for answer.
According to the Unity Documentation, this "Transforms position from local space to world space." So I think this is a better answer.
Your answer
Follow this Question
Related Questions
Why vertex positions appear (0.0, 0.0, 0.0) ? 1 Answer
MeshCollider is not getting updated when adding vertex to mesh 1 Answer
Is it possible to make vertices defined by a mesh and mesh filters animating? 0 Answers
NullReferenceException on assigning vector3 to mesh.vertices - no effect on assignment? 1 Answer