- Home /
Coroutine Moving
My script is intended to move a gameobject towards an object called "cursor." I'm trying to get the script to launch in a coroutine so it recalculates where it's supposed to go when I click a second time. I'm pretty sure I'm not doing it right because the gameobject doesn't move at all. Here is my script:
public Vector3 startMarker;
public Vector3 endMarker;
public GameObject point;
public float speed;
private float startTime;
private float journeyLength;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
startMarker = gameObject.transform.position;
endMarker = GameObject.Find("Cursor").transform.position;
StartCoroutine(Move());
}
IEnumerator Move()
{
startTime = Time.time;
journeyLength = Vector3.Distance(startMarker, endMarker);
float distCovered = (Time.time - startTime) * speed;
float fractionOfJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(startMarker, endMarker, fractionOfJourney);
}
}
It seems like I'm missing something pretty simple, but I can't spot it... Thanks for helping!
Answer by PlayCreatively · Aug 22, 2020 at 08:34 AM
First of all you're not iterating in your routine so it just runs once, however the rest of the logic didn't make much sense anyways so I wrote something different. Haven't tried it but hope it helps.
IEnumerator Move()
{
float journeyLength = Vector3.Distance(startMarker, endMarker);
float endTime = Time.time + journeyLength / speed;
while (Time.time < endTime)
{
transform.position = Vector3.Lerp(startMarker, endMarker, Time.time / endTime);
yield return null;
}
}
Your answer
Follow this Question
Related Questions
rotate object by list values 0 Answers
MouseWheel Lerp Smoothing Problem 1 Answer
Can my lerp-function be optimized? 1 Answer
Kind of Lag in movement 2 Answers
Unity 2D Scripted Movement 2 Answers