I have several line renderers that are using as gas pipelines. A user can select one end of the pipe and attach it to one connector. Now the problem is some pipes (line renderer) are overlapping and penetrating with each other. Is there any way to avoid penetration using colliders so they look realistic?
Yes It can be done, it requires a bit manipulation with vectors.
LineRenderer has start and finish, capsule colider has height,and all features of its transform. OK lets convert LineRenderer data to capsule collider!
The steps are as follows:
LineRenderer has start and finish coordinates - get them by using LineRenderer.GetPosition(0) and LineRenderer.GetPosition(1). So now you know where line starts and ends. Lets call them startPos and endPos.
lets find out height of CapsuleCollider. To do that just subtract:
Vector3 dir = endPos-startPos; ///---this is vector that points from starting point to finish point float height = dir.magnitude;
now we have height!
Lets get the middle point of this line. To do this you halve the vector and add startPos vector to it:
Vector3 dir2 = dir * 0.5f; Vector3 centerCoord = startPos + dir2;
we got the center of line!
Lets get the all 3 angles - the rotation of the line:
float angleWithZ =Vector3.Angle(dir,new Vector3(0,0,1)); float angleWithY =Vector3.Angle(dir,new Vector3(0,1,0)); float angleWithX =Vector3.Angle(dir,new Vector3(1,0,0));
We have all the angles!
Now just use an empty game object - (if unchecked "use world space" then child to parent and a brother of your line), set its position to our centerCoord , add capsule collider, set its height,(dont forget to zero its center) and rotate this transform according our angles!
write all this into neat script, add it to Update() function (or coroutine) and colliders will position themselves automatically!