I am using the code below to create shapes with a line renderer based on the number of points. For points greater than 3 (triangle shape and so on) the first and last points don't close the shape in the the way that the other points do.
1.How can close shapes with more than 3 points without any visible gaps?
2.How can I animate the shape so it draws the lines over a specific duration (possibly using a coroutine)?
public class CircleDrawing : MonoBehaviour
{
[Tooltip("The radius of the circle, measured in world units.")]
public float Radius = 2;
[Tooltip("The number of vertices in the circle.")]
public int Points = 5;
[Tooltip("The color of the circle.")]
public Color Color;
private LineRenderer lineRenderer;
public void Awake()
{
lineRenderer = gameObject.AddComponent<LineRenderer>();
lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
lineRenderer.material.color = Color;
lineRenderer.startWidth = lineRenderer.endWidth = 0.5f;
lineRenderer.positionCount = Points + 1; //+1 to close the shape
Draw();
}
private void Draw()
{
float angle = 0f;
for (int i = 0; i <= Points; i++)
{
float x = Radius * Mathf.Cos(angle) + transform.position.x;
float y = Radius * Mathf.Sin(angle) + transform.position.y;
lineRenderer.SetPosition(i, new Vector3(x, y, 0.01f)); //Z is slightly behind the paddle so it draws in front
angle += (2f * Mathf.PI) / Points;
}
}
private void OnDestroy()
{
Destroy(lineRenderer.material);
}
}
Here's a script that I used on my dotted line prefab (attached to the same object that has the LineRenderer component): using UnityEngine; public class DottedLineRenderer : MonoBehaviour { public bool scaleInUpdate = false; private LineRenderer lR; private Renderer rend; private void Start ()
If you make sure that the last point of your LineRenderer is the same as the first point it should always close any given shape. Run the for
loop like this for (int i = 0; i < Points - 1; i++)
(so each point but the last one, also <
and not <=
). Then close the shape with lineRenderer.SetPosition(Point - 1, lineRenderer.GetPosition(0));
when the for loop is done.
Note here that Arrays start at 0, that's why Point - 1
is the last point of your lineRenderer.
For the animation I don't know an easy way to do it. What I would do is use a coroutine to move each point toward is final destination over time. For example you start by adding the first point and you add the second point on top of the first point. Then you move (over time in a coroutine) the second point toward it's final position (use SetPosition
to move it). When it has reached it's final position add the third point on top of it, and move it to it's final position. Repeat for every points.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With