- Home /
How to give a position an offset relative to its forward vector in local space?
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.
Answer by Captain_Pineapple · Apr 08 at 01:04 PM
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.
That's such an elegant solution! I was just trying stuff like rotating the forward vector by 45 degrees and stuff but this makes way more sense. Thanks!
Doing this with rotations is also very much a possible solution! As this would be more complex and more taxing regarding performance the pure vector calculations are more favorable for a real application though.
Your answer
Follow this Question
Related Questions
How to get a vector3 (postion) 1 unit away from another in the direction of a 3rd vector3? 2 Answers
Please help, bullet drop is wrong at certain angles ? 0 Answers
How to get translation from matrix? 1 Answer
Project a position onto a plane whose normal isn't at the origin. 2 Answers
How can I calculate the Vector3 b using Vector 3 a pos with an angle? 1 Answer