How to complete smooth movement without using StartCoroutine and IEnumerate?

protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
{
Vector2 start = transform.position;
Vector2 end = start + new Vector2(xDir, yDir);
boxCollider.enabled = false;
hit = Physics2D.Linecast(start, end, blockingLayer);
boxCollider.enabled = true;
if (hit.transform == null)
{
StartCoroutine(SmoothMovement(end)); // Code I want to change
//SmoothMovement(end);
return true;
}
return false;
}
//protected void SmoothMovement(Vector3 end)
protected IEnumerator SmoothMovement(Vector3 end)
{
float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
while (sqrRemainingDistance > float.Epsilon)
{
Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.fixedDeltaTime);
rb2D.MovePosition(newPostion);
sqrRemainingDistance = (transform.position - end).sqrMagnitude;
yield return null;
}
//return; //Code I want to change
}
The code below tells if there is a block in Player’s path, if not, smoothly move to the end. I try to modify the code without using “StartCoroutine” and “IEnemerator”.

The modify points are as following : Firstly I use SmoothMovement(end) instead of StartCoroutine(SmoothMovement(end)). And then change "IEnumerator SM " function to “void SM” function, as well as commenting “yield return null”. However this dont work and my game stucks, could anyone tell me what’s wrong?

When you stop using coroutine, it will only run once. Coroutines run in the background until they are finished. To fix this you need to continuously call SmoothMovement to move towards the end.

I recommend that you save the end in a variable in the class, and in update call SmoothMovement.