Make a sphere move in the line renderer between two points?

by Mohammed Saif S D K   Last Updated June 13, 2019 08:26 AM

I have a line renderer component that is drawn between two gameObjects. How do I create a sphere that travels between these two gameObjects? For example, is starts at Point A and travels till Point B and then it returns from Point B to Point 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);
    }

}
Tags : c# unity3d


Answers 1


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;
    }
}

}

Just added a while loop at the start with Coroutine that works in an infinite loop.

Mohammed Saif S D K
Mohammed Saif S D K
June 13, 2019 08:25 AM

Related Questions


Updated February 19, 2017 19:26 PM

Updated October 09, 2017 06:26 AM

Updated October 19, 2018 06:26 AM

Updated February 14, 2018 06:26 AM