使球体在直线渲染器中在两个点之间移动?

时间:2019-06-13 07:53:31

标签: c# unity3d

我有一个在两个gameObjects之间绘制的线条渲染器组件。如何创建在这两个游戏对象之间传播的球体?例如,从点A开始,一直到点B,然后从点B返回点A。

public class DrawLine : MonoBehaviour
{
    public GameObject PointA;
    public GameObject PointB;
    public float lineWidth;
    private LineRenderer lineRenderer;


    void Start()
    {
        lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.SetWidth(lineWidth,lineWidth);
    }

    void Update()
    {
        lineRenderer.SetPosition(0, PointA.transform.localPosition);
        lineRenderer.SetPosition(1, PointB.transform.localPosition);
    }

}

1 个答案:

答案 0 :(得分:0)

public class DrawLine : MonoBehaviour
{

    public GameObject PointA;
    public GameObject PointB;
    public float lineWidth;
    private LineRenderer lineRenderer;
    GameObject sphere;
    public float speedOfSphere = 1f;
    public float TimeToStart;
    private bool StartAhead = true;
    public Material SphereMaterial;
    public Material LineRendererMaterial;

    IEnumerator Start()
    {
        lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.SetWidth(lineWidth, lineWidth);
        sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        sphere.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
        lineRenderer.SetPosition(0, PointA.transform.localPosition);
        lineRenderer.SetPosition(1, PointB.transform.localPosition);
        lineRenderer.material = LineRendererMaterial;

        sphere.transform.position = PointA.transform.position;
        sphere.GetComponent<Renderer>().material = SphereMaterial;

        while (true)
        {
            if(StartAhead==true)
            {
                yield return new WaitForSeconds(TimeToStart);
                StartAhead = false;
            }

            yield return StartCoroutine(MoveObject(sphere.transform, PointA.transform.position, PointB.transform.position, speedOfSphere));
            yield return StartCoroutine(MoveObject(sphere.transform, PointB.transform.position, PointA.transform.position, speedOfSphere));
        }

    }


    IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time)
    {
        var i = 0.0f;
        var rate = 1.0f / time;
        while (i < 1.0f)
        {
            i += Time.deltaTime * rate;
            thisTransform.position = Vector3.Lerp(startPos, endPos, i);
            yield return null;
        }
    }

}

只需在Coroutine的开头添加一个while循环,即可在无限循环中工作。