- Home /
Crash on loop using Lerp.
My code crashes whenever I click...
void Update ()
{
if (Input.GetMouseButtonDown (0) == true)
{
StartCoroutine(OnLClick());
}
}
IEnumerator OnLClick ()
{
yield return new WaitForSeconds(.01f);
Vector3 stwpCamera = Camera.main.ScreenToWorldPoint (Input.mousePosition);
while (!(transform.position == stwpCamera))
{
transform.position = Vector3.Lerp (transform.position, new Vector3(stwpCamera.x, stwpCamera.y, -10), Time.deltaTime);
}
}
Any help would be greatly appreciated.
Answer by HarshadK · Aug 13, 2014 at 11:31 AM
Do not compare your positions using == in your while because these values are float and it's unlikely that floats will be exactly equal. Since your two values are not equal your while loop is infinite.
Use Mathf.Approximately to compare floats.
So your while loop condition will be
while(!(Mathf.Approximately(transform.position,stwpCamera)))
While this was helpful, transform.position and stwpCamera are both Vector3, and this attempted to convert them into floats. I fixed this by comparing each value (x,y,z). The code compiled correctly, but looped and crashed all the same.
while(!(($$anonymous$$athf.Approximately(transform.position.x,stwpCamera.x))&&($$anonymous$$athf.Approximately(transform.position.y,stwpCamera.y))&&($$anonymous$$athf.Approximately(transform.position.z,stwpCamera.z))));
Your answer
Follow this Question
Related Questions
Why is this coroutine only firing once? 3 Answers
Infinite Looping Crash 2 Answers
Third person Camera With Lerp trouble 0 Answers
Modified SmoothFollow 0 Answers