- Home /
Smoothly moving a 2D gameobject along a vector path
I have a method named Movement() being called in Update() that is supposed to smoothly move my 2D gameobject along a path derived from a list of vectors. My code works but i can't seem to alter the speed at which the gameobject travels along the path. I suspect its because each frame, MoveTowards is being called with a new starting point and target destination but i need it to be called it update because the path can and probably will get updated by the player and the gameobject/s will need to respond accordingly (continue to travel along the path). I have an idea of how to work around this but its kinda complicated and i would rather avoid it if possible. So i would like to ask if there's some sort of simple solution to my problem that exists. Any help would be much appreciated.
private void Movement()
{
if (pathVectorList != null)
{
if (currentTargetIndex < pathVectorList.Count)
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(pathVectorList[currentTargetIndex - 1], pathVectorList[currentTargetIndex], step);
currentTargetIndex++;
}
}
}
Answer by dimtreo · Jul 08, 2020 at 03:02 PM
Looking at the code I'd imagine that your suspicion is correct. Every time Movement() is called it increments the target index which results in instant jump to the start of the next target. You could increment your target index only if you are close enough to your current target. I'd imagine something like this should work:
private void Movement()
{
if (pathVectorList != null)
{
if (currentTargetIndex < pathVectorList.Count)
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, pathVectorList[currentTargetIndex], step);
if (Vector3.Distance(transform.position, pathVectorList[currentTargetIndex]) < 0.01)
{
currentTargetIndex++;
}
}
}
}
Your answer
Follow this Question
Related Questions
conserve momentum of vector3.moveTowards in 2D game 0 Answers
Update LineRenderer every frame (Delete Old Lines) 1 Answer
Cant change transform.position of gameobject 1 Answer
Unity smooth following 2D camera not working properly on different resolutions 0 Answers
Shotting Or thrwoing Object wtih Vector3.MoveTowards 1 Answer