Drawing from origin to each vertex on an object

Hi there, I’m doing a raycast to determine which object the mouse is over. Once this is done, I want check the vertex closest to that point within the object.

To start off with, just to ensure I understand what I’m doing, once an object is clicked, I’m looping through all the vertices and drawing a line between hte objects transform and the vertex as below:

	void GetandDraw ()
	{
		mesh = GetComponent<MeshFilter> ().mesh;
		vertices = mesh.vertices;
		DrawVertices ();

	}
	
	void DrawVertices ()
	{
		foreach (Vector3 vertex in vertices) {
			// A plane is stored in x and z, so we need to make the z the y
			Vector3 newVertex = new Vector3 (vertex.x, vertex.z, vertex.y);
			
			Debug.DrawLine (transform.position, transform.position + newVertex, Color.red, 10.0f);	
		}
 
	}

I dont understand the result I’m getting (the little bundle of read lines at the position of hte plane) - the ‘shape’ seems to be correct (the bundle of lines seem to be stretching towards each vertex), but come considerably short of reaching them. It looks as if I need to scale the vertex positions to get the result I’m after, but I don’t understand why?

BTW I should add the solitary red line is the raycast.

So this now makes it work: Vector3 newVertex = new Vector3 (vertex.x * transform.localScale.x, vertex.z * transform.localScale.z, vertex.y); I don't understand why I need to scale this up - surely a vertex is an absolute position?

1 Answer

1

Vertex positions are stored locally, relative to the object. You need to convert them to World Space.

foreach (Vector3 vertex in vertices) {
    Vector3 vertexWorldPos = vertObject.TransformPoint(vertex);
    Debug.DrawLine (transform.position, vertexWorldPos, Color.red, 10.0f);  
}

I didnt read your entire post :slight_smile: But im pretty sure this is what you want!

works a treat, thanks