使用LineRenderer

时间:2018-06-05 16:40:23

标签: c# unity3d

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;

    public bool circle = true;
    [Range(0, 50)]
    public float xradius = 15;
    [Range(0, 50)]
    public float yradius = 15;
    LineRenderer line;

    public float drawSpeed = 0.3f;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = (segments + 1);
        line.useWorldSpace = false;

        StartCoroutine(CreatePoints());
    }

    IEnumerator CreatePoints()
    {
        if (circle == true)
            yradius = xradius;

        float x;
        float z;

        float change = 2 * (float)Math.PI / segments;
        float angle = change;

        x = Mathf.Sin(angle) * xradius;
        line.SetPosition(0, new Vector3(x, 0.5f, 0));

        for (int i = 1; i < (segments); i++)
        {
            x = Mathf.Sin(angle) * xradius;
            z = Mathf.Cos(angle) * yradius;

            yield return new WaitForSeconds(drawSpeed);
            line.SetPosition((int)i, new Vector3(x, 0.5f, z));

            angle += change;
        }
    }
}

当我想要运行游戏时,它将从已经从圆心开始绘制的索引0开始。所以我在循环之前添加了这两行:

x = Mathf.Sin(angle) * xradius;
line.SetPosition(0, new Vector3(x, 0.5f, 0));

在添加这两行之前,for循环是:

for (int i = 0; i < (segments + 1); i++)

但是现在我想从索引1开始循环,所以我尝试了:

for (int i = 1; i < (segments); i++)

但它没有完整的一轮:

Circle

圆形绘图正在顺时针方向移动。

1 个答案:

答案 0 :(得分:2)

你不是从0开始

float angle = change; //change is > 0

出于解释的目的,我假设change为10度。

因此,您的第一段从中心到圆圈周围的10度点。

你应该这样做:

    float angle = 0;

    x = Mathf.Sin(angle) * xradius;
    line.SetPosition(0, new Vector3(x, 0.5f, 0));