如何在不留空隙的情况下为线条渲染器形状设置动画

Its*_*ain 17 c# unity-game-engine

我正在使用下面的代码根据点数创建带有线条渲染器的形状.对于大于3的点(三角形等),第一个和最后一个点不会像其他点那样关闭形状.

1.如何在没有任何可见间隙的情况下关闭超过3个点的形状?

2.如何设置形状的动画,以便在特定的持续时间内绘制线条(可能使用协程)?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 1

如果您确保 LineRenderer 的最后一个点与第一个点相同,它应该始终闭合任何给定的形状。for像这样运行循环for (int i = 0; i < Points - 1; i++)(所以除了最后一个点之外的每个点,也而<不是<=)。lineRenderer.SetPosition(Point - 1, lineRenderer.GetPosition(0));然后,当 for 循环完成时,关闭形状。

请注意,数组从 0 开始,这就是为什么Point - 1是 lineRenderer 的最后一个点。

对于动画,我不知道有什么简单的方法可以做到。我要做的是使用协程随着时间的推移将每个点移向最终目的地。例如,您首先添加第一个点,然后在第一个点的顶部添加第二个点。然后(在协程中随着时间的推移)将第二个点移向其最终位置(使用SetPosition来移动它)。当它到达最终位置时,在其顶部添加第三个点,并将其移动到最终位置。对每个点重复此操作。