- Home /
Drawing a line between 2 canvas RectTransform objects
I've been trying to draw a line (animated) between 2 points. The points being the center's of 2 Rectransforms as part of the UI - think, animating a line between 2 points on a game map for a 2D game.
What I have so far:
private LineRenderer lineRenderer;
private float lineDrawSpeed = 6f;
private float dist;
private float counter;
public RectTransform stage1Point;
public RectTransform stage2Point;
private Vector3 stage1Pos;
private Vector3 stage2Pos;
void Start() {
Camera camera = Grid.camera.GetCamera ();
// I have tried a number of ways to try and convert these so it draws correctly but failing :(
stage1Pos = stage1Point.position;
stage2Pos = stage2Point.position;
lineRenderer = GetComponent<LineRenderer> ();
lineRenderer.SetPosition (0, stage1Pos);
lineRenderer.SetPosition (1, stage2Pos);
lineRenderer.SetWidth (0.3f, 0.3f);
dist = Vector3.Distance (stage1Pos, stage2Pos);
}
void Update() {
if (counter < dist) {
counter += .1f / lineDrawSpeed;
float x = Mathf.Lerp (0, dist, counter);
Vector3 pointA = stage1Pos;
Vector3 pointB = stage2Pos;
Vector3 pointAlongTheLine = x * Vector3.Normalize (pointA - pointB) + pointA;
lineRenderer.SetPosition (1, pointAlongTheLine);
}
}
The line draws, but goes off at z angles and strange positions. I'm pretty certain it's to do with the co-ordinate calculations but can't wrap my head around it. Cheers.
Answer by mikey555 · Feb 21, 2016 at 04:25 PM
I did it with a coroutine. It's a bit neater than putting things in Update! I recommend learning something about coroutines if you haven't. In a nutshell, the line 'return yield null' tells Unity to wait until the next frame to continue. This will draw a line between two points. You could modify it fairly easily to add more points.
public class Lines : MonoBehaviour {
LineRenderer lr;
public RectTransform stage1;
public RectTransform stage2;
public float speed;
void Awake()
{
lr = GetComponent<LineRenderer>();
}
void Start()
{
lr.SetVertexCount(2);
lr.SetWidth(0.3f, 0.3f);
StartCoroutine(AnimateLineBetween(stage1, stage2));
}
IEnumerator AnimateLineBetween(RectTransform a, RectTransform b)
{
// set first point
lr.SetPosition(0, a.anchoredPosition3D);
// initialize second point
lr.SetPosition(1, a.anchoredPosition3D);
// the distance (and direction) between the two points
Vector3 distance = b.anchoredPosition3D - a.anchoredPosition3D;
for (float i = 0; i < 1; i += speed / 200)
{
// each frame, advance a fraction of the way
lr.SetPosition(1, distance * i);
yield return null;
}
}
}