I’m trying to generate a mesh to display connected segments representing street lines in a mini map. I have problem with vertex orientation that my math knowledge has hard time to resolve.
Let’s consider 3 points p0, p1 and p2.
I use this code to create the vertices from the segment between p0 and p1 (the same code is then used for the segment from p1 to p2):
height = 2.0f; // desired line thickness
vertices[0] = new Vector3(p0.position.x, p0.position.y - height / 2.0f, 0);
vertices[1] = new Vector3(p1.position.x, p1.position.y - height / 2.0f, 0);
vertices[2] = new Vector3(p0.position.x, p0.position.y + height / 2.0f, 0);
vertices[3] = new Vector3(p1.position.x, p1.position.y + height / 2.0f, 0);
The result looks like this:
Not that bad, except that the "thickness" of the line is not constant. If you look closely to the segment left and right borders, they are aligned (going from bottom to top). The problem comes from the “height” variable that is added or subtracted too naively to the positions.
What I’d like to have is something like this, with oriented borders / vertex.
However I don’t know how to proceed.
Any help or comment would be appreciated. Thanks for your time.
**** EDIT **** Thanks to @wondra's solution I managed to do what I needed to. Here is how:
// Returns point of intersection
// TODO: check if lines are parallel
public Vector3 LineIntersection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
float ma = (p2.y - p1.y) / (p2.x - p1.x);
float mb = (p4.y - p3.y) / (p4.x - p3.x);
float ba = p1.y - (p1.x * ma);
float bb = p3.y - (p3.x * mb);
float x = -(ba - bb) / (ma - mb);
float y = ma * x + ba;
return new Vector3(x, y);
}
/// --- LOOPING THROUGH POINTS ---
// @wondra's solution
Vector2 dir = (sec_node.position - prim_node.position).normalized;
Vector2 perp = new Vector2(dir.y, -dir.x);
vertices[vert_idx] = prim_node.position + (perp * -height / 2.0f);
vertices[vert_idx + 1] = sec_node.position + (perp * -height / 2.0f);
vertices[vert_idx + 2] = prim_node.position + (perp * height / 2.0f);
vertices[vert_idx + 3] = sec_node.position + (perp * height / 2.0f);
if ( vert_idx > 4 )
{
int vert_idx_bis = vert_idx - 4;
vertices[vert_idx] = LineIntersection(vertices[vert_idx], vertices[vert_idx + 1], vertices[vert_idx_bis + 1], vertices[vert_idx_bis]);
vertices[vert_idx_bis + 1] = vertices[vert_idx];
vertices[vert_idx + 2] = LineIntersection(vertices[vert_idx + 2], vertices[vert_idx + 3], vertices[vert_idx_bis + 3], vertices[vert_idx_bis + 2]);
vertices[vert_idx_bis + 3] = vertices[vert_idx + 2];
}
/// --- END LOOP