- Home /
How to recognise every vertices's position in model and keep track of them in scene window?
For example. I created a quad and I want to draw lines from camera‘s position to quad‘s vertices. Also I want to mark every vertex of this quad. so I wrote code like this:
private Vector3 cameraPos;
public MeshFilter meshFilter;
public float radius;
void Start()
{
cameraPos = GetComponent<Camera>().transform.position;
}
[ExecuteInEditMode]
void Update()
{
for (int i = 0; i < meshFilter.mesh.vertexCount; i++)
{
Debug.DrawRay(cameraPos, meshFilter.mesh.vertices[i], Color.green);
}
}
private void OnDrawGizmos()
{
for (int i = 0; i < meshFilter.sharedMesh.vertexCount; i++)
{
Gizmos.DrawWireSphere(meshFilter.mesh.vertices[i], radius);
}
}
But it turns out the line doesn‘t connect camera and quad's vertex. The Gizmos sphere I drew seems right with its position,but when I scale the quad,the sphere‘s position won't match its positions with my new quad‘s vertices's position,just stay in there.
Plz tell me how can I fix this problem?
now a month passed,is there anybody can help me to figure it out?
Answer by Bunny83 · Dec 01, 2017 at 06:24 PM
There are two things you should and have to change. First of all you shouldn't use mesh.vertices the way you do. vertices is a property that will allocated a new array everytime you read it. That means each loop iteration you create a new vertices array. You should read the array once and then access the array.
Your second problem is that the vertices are defined in local space of the object. However the gizmos are drawn in world space. So the objects position, rotation and scale is not taken into account. You have to convert every localspace position into worldspace. This is done by using TransformPoint of the Transform of your object.
Something like this:
private Transform camTrans;
private Transform mfTrans;
public MeshFilter meshFilter;
public float radius;
private Vector3[] vertices;
void Start()
{
camTrans = GetComponent<Camera>().transform;
mfTrans = meshFilter.transform;
}
[ExecuteInEditMode]
void Update()
{
if (vertices == null)
vertices = meshFilter.sharedMesh.vertices;
Transform mfTrans = meshFilter.transform;
for (int i = 0; i < vertices.Length; i++)
{
Vector3 wPos = mfTrans.TransformPoint(vertices[i]);
Debug.DrawRay(camTrans.position, wPos, Color.green);
}
}
private void OnDrawGizmos()
{
for (int i = 0; i < vertices.Length; i++)
{
Vector3 wPos = mfTrans.TransformPoint(vertices[i]);
Gizmos.DrawWireSphere(wPos, radius);
}
}
Your answer
Follow this Question
Related Questions
Editor Gizmo logic question? How do the gizmos move relative to camera 1 Answer
Get position of the closest visible vertex to mouse in scene view? 1 Answer
Converting Mesh to Set of Discrete Coordinates 1 Answer
How magenta cyrcle to follow to Z-axis when dark red rectangle rotating? 0 Answers
Select a face of an object ingame 3 Answers