I want to achieve smooth object move from actual position to another position after mouse click. I’m using MoveTowards function in Update method.
Another position is defined as empty object attached to parameter “wayPoint”
Problem was, that after mouse click has object moved just in one frame towards destination position. So I tried to prevent it with Coroutine, but even with that is result still the same. An object is still moving just in one frame and not the whole path from start to destination. And I have to click every frame to move it towards destination.
My code is below. Does anybody know, where can be a problem? Thanks for any response.
[SerializeField] float speed = 20f;
[SerializeField] Transform wayPoint;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(MoveTo(transform.position, wayPoint.transform.position, speed));
}
}
IEnumerator MoveTo(Vector2 start, Vector2 destination, float speed)
{
transform.position = Vector2.MoveTowards(start, destination, speed * Time.deltaTime);
yield return null;
}
MoveTowards
is not a magic function that automatically move an object over time. It’s just a function helping you determining a new position between two points.
Calculate a position between the points specified by current and target, moving no farther than the distance specified by maxDistanceDelta
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StopAllCoroutines();
StartCoroutine(MoveTo(transform.position, wayPoint.transform.position, speed));
}
}
IEnumerator MoveTo(Vector2 start, Vector2 destination, float speed)
{
while( (transform.position - destination).sqrMagnitude > 0.01f )
{
transform.position = Vector2.MoveTowards(transform.position, destination, speed * Time.deltaTime);
yield return null;
}
}
Thanks for answer @Hellium
Yes, that makes sense. I added WHILE loop to the coroutine, but unfortunately, results are still the same. Update is still waiting for new mouse click every frame to move it closer to the destination. So it’s moving just a small piece every frame.
Works perfectly now. Thank you @Hellium. I very appreciate your help. I would probably spend days to solve it.
@Hellium. Accepted. Sorry, I’m newbie here.
I also noticed that “start” config parameter in coroutine declaration is now unnecessary and can be removed completely (also in Update, where coroutine is called). Because it’s not used anywhere. So “destination” and “speed” parameters are enough to run this.
Just for clarification for someone in the future.