- Home /
Find Vector3 point exactly between two gameobjects with an offset perpendicular to the line connecting the two gameobjects
I am using a linerenderer (called line) to create a bezier curve between two gameobjects like this (C#):
float t;
Vector3 position;
for(int ii = 0; ii < 32 /* amount of line segments */; ii++)
{
t = ii / (32F - 1F);
position = (1F - t) * (1F - t) * object1.transform.position
+ 2F * (1F - t) * t * Vector3.zero
+ t * t * object2.transform.position;
line.SetPosition(ii, position);
}
Right now, the control point is Vector3.zero. I want the control point to be exactly between the two gameobjects with an offset perpendicular to the line connecting the two gameobjects. A quick sketch included in this question shows what I want to achieve:
[1]: /storage/temp/26296-controlpointbezier.png
When I would try something like this in a 2d setting, I would have used some simple trigonometry, but I'm quite new to 3d graphics and am not sure how to work this out.
As Lootnitik notes in the comment, in 3D space, "perpendicular to a line" could be lots of lines. You have to decide "perpendicular to what else"? Like to the camera, or the first object's facing. And even then it can go left or right.
It's not really 3D graphics -- just 3D geometry.
Answer by NickP_2 · May 07, 2014 at 12:51 PM
The midpoint between 2 vectors is as easy as (vector1 + vector2)/2. Add vector.up (if it needs to be on the y axis) times a certain amount. Hope it helps
Finding the midpoint works, thanks! The vector.up works on the y-axis indeed, but I want to place the control point with an offset perpendicular to the line connecting the two gameobjects, this is the most difficult part I think...
Try integrating something like this into your code.
Transform t1 = someTrans ;
Transform t2 = someOtherTrans ;
float offset = someFloatValue ;
Vector3 GetPoint()
{
//get the positions of our transforms
Vector3 pos1 = t1.position ;
Vector3 pos2 = t2.position ;
//get the direction between the two transforms -->
Vector3 dir = (pos2 - pos1).normalized ;
//get a direction that crosses our [dir] direction
//NOTE! : this can be any of a buhgillion directions that cross our [dir] in 3D space
//To alter which direction we're crossing in, assign another directional value to the 2nd parameter
Vector3 perpDir = Vector3.Cross(dir, Vector3.right) ;
//get our midway point
Vector3 midPoint = (pos1 + pos2) / 2f ;
//get the offset point
//This is the point you're looking for.
Vector3 offsetPoint = midPoint + (perpDir * offset) ;
return offsetPoint ;
}
void Some$$anonymous$$ethodToDoStuff()
{
Vector3 point = GetPoint() ;
//do whatever else with the point now...
}
If the drawing is 2D on the XY plane, then Vector3.forward rathar than Vector3.right for the Cross().