- Home /
Make a dynamic visual link between two game objects
I have two ships and a planet in between. I want to make a visual link between the ships but in a way that the link will arc around the planet, but not trough it.
I also want this to be dynamic, for example when I select one of the ships and move it with arrow keys. I want the line link to adapt and change to the new position of the ship dynamically.
I thought maybe LineRenderer but that is just a straight line. Any ideas how can I achieve this is unity? Is there some component that I could possibliy use and adapt to this scenario?
thanks.
Answer by cjdev · Sep 24, 2015 at 09:46 PM
While the line renderer only renders straight lines between two points it can render an arbitrary amount of them in succession between different points. This allows you to render a curve with a resolution dependent on the number of line segments in your renderer.
To set a curve like the one in your picture you'd be much better off splitting it into two curves, one that goes to the high point above the planet and one that continues to the next ship. Using a curve equation of your choice, my personal favorite is the Bezier equation, you can then get the positions of each of the vertices that goes into your SetPostion LineRenderer method. If you're not familiar with it, a Bezier curve consists of 4 points: the beginning and end plus a control point for each that determines the curve and direction the curve begins and ends at each point. It looks something like this:
Where 0 and 3 are the beginning and end, 1 is the control point for the beginning and 2 for the end. The control points effectively pull the curve in their direction so they can be adjusted depending on how you need the curve to look accordingly. The code for it is surprisingly simple:
private Vector3 Bezier(float t)
{
float mt = 1 - t;
float x = mt * mt * mt * bezierPoints[0].x + 3 * mt * mt * t * bezierPoints[1].x + 3 * mt * t * t * bezierPoints[2].x + t * t * t * bezierPoints[3].x;
float y = mt * mt * mt * bezierPoints[0].y + 3 * mt * mt * t * bezierPoints[1].y + 3 * mt * t * t * bezierPoints[2].y + t * t * t * bezierPoints[3].y;
float z = mt * mt * mt * bezierPoints[0].z + 3 * mt * mt * t * bezierPoints[1].z + 3 * mt * t * t * bezierPoints[2].z + t * t * t * bezierPoints[3].z;
return new Vector3(x, y, z);
}
This will get you a Vector3 at a percentage 0 - 1.0f along the bezier curve defined by the list bezierPoints with indices of points like those shown in the picture above. So to make your line renderer into a curve you would use SetPosition and iterate over your total points with something like Bezier(i / totalPoints)
.