Hi, I hope someone can help me with this, I know how to work in 2D but now I’m trying out something in 3D.
What i want to achieve is:
- 2 objects with different rotation values are placed on a scene.
- Connect the object via a tube.
- The tube connector is placed pointing to the other object. (Image red circle)
My problem is, I can get the direction and so on, but this will place the object underneath the red circle, just where the blue line hits the mesh.
Can someone please help me or tell me how i can calculate the orange line pointing to the red circle?
Hey there,
there are multiple ways to solve this but for this the easiest way is probably to use the power of the cross-product.
basically the result of a cross product of 2 vectors is a vector that is perpendicular to both vectors.
So if we define:
- Left end of your lightblue line is
P1
- Right end of your lightblue line is
P2
- z-Axis through your left zylinder is
cylinder_up
- radius of your zylinder left is
cylinder_R
Then you can calculate the point you are looking for by:
var PointOnSurface = CenterOfLeftCylinder + (Vector3.Cross(Vector3.Cross(P2-P1,cylinder_up),cylinder_up).normalized * cylinder_R;
Basically Vector3.Cross(P2-P1,cylinder_up)
calculates a helping vector which is perpendicular to your connectionLine P2-P1 and cylinder z Axis. Then taking the cross product with cylinder_up again gives you the line you want. (you might have to add a minus to the resulting normalized vector or switch the arguments of the cross product around since there are always 2 vectors that can be the result of the cross product. So depending on how unity works below the surface the resulting vector might point in the wrong direction by 180°.)
Let me know if that helped/something was unclear.