In my road creation tool, I want to create a road out of 2 points. In order to do that I need to create a box of vertexes where 4 points surround the 2 initial points. However, I am struggling to find out where to place those points when the road is at an angle. I have the feeling it might be something really easy but my brain is just not cathcing it.
The difference in the example is really small but I hope it makes clear what I am trying to achieve. if you need any initial information feel free to ask but I hope the illustration speaks for itself.
Yes that illustration is enough.
So if we assume you have a starting point and endpoint and an offset:
Vector2 startpoint = new Vector2(x1, y1);
Vector2 endpoint = new Vector2(x2, y2);
float offset = 3;
Then you can calulate the following vectors:
//connect the red dots, get the vector and shorten it to length 1:
Vector2 direction_normalized = (endpoint - startpoint).normalized;
// get the perpendicular vector: (normalization might not be needed here - not sure):
Vector2 direction_perpendicular = Vector2.perpendicular(direction_normalized).normalized;
Then the 4 points you are searching for are:
Vector2 P1 = startpoint + offset*(-direction_normalized + direction_perpendicular);
Vector2 P2 = startpoint + offset*(-direction_normalized - direction_perpendicular);
Vector2 P3 = endpoint + offset*(direction_normalized - direction_perpendicular);
Vector2 P4 = endpoint + offset*(direction_normalized - direction_perpendicular);
This can ofc also be done in 3D space. Only thing to change in that regard is that 3D space does not contain a simple “perpendicular” function. There you’d have to learn to use the cross product. (Vector3.cross(v1, v2)
)
Let me know if something was unclear.