- Home /
Vector2.MoveTowards not working
Hi all,
I'm sure this is a rookie mistake but I've followed another example and the solution Given seems to be exactly what I've got - I'm missing something obvious. Here is the code:
void Start () {
CurrPos = transform.position;
NewPos = transform.position + (transform.up*4.0f);
}
// Update is called once per frame
void Update () {
Debug.Log ("CurrPos: " + CurrPos + ", NewPos: " + NewPos + ", ActualPos" + transform.position);
transform.position = Vector2.MoveTowards (CurrPos, NewPos, 10.0f * Time.deltaTime);
}
The Debug outputs all the correct values, but the transform.position never changes.
Apologies for the noob question, but any help would be appreciated.
Answer by JVene · Nov 11, 2018 at 06:19 PM
Consider the 3rd parameter you're providing to MoveTowards, 10.0f * Time.deltaTime. When the engine is limiting frame rate to the refresh rate, this usually means something like a constant 60 frames per second, such that Time.deltaTime is always 1/60th of a second (assuming the graphics isn't heavy so the rate is always high).
That would mean that 10.0f * Time.deltaTime always returns the same number. MoveTowards is a version of a lerp, an interpolation between two values ( CurrPos & NewPos ) based on a ratio in the range of 0 to 1. The closer to 0, the closer the result is CurrPos, the closer to 1.0 the closer the result is to NewPos. However, in your example, it is likely that this value, the ratio you're providing, is stick close to zero - about .0.166667.
What you need to do is increment time. When this motion begins, the value you provide as this ratio should be about 0. Create and set an "accumulatedTime" float to zero to begin this. If you want the event to take 10 seconds, then you want this ratio to reach 1.0 when 10 seconds has elapsed. So, accumulatedTime / 10.0f would do that.
What you use Time.deltaTime for is when INCREMENTING accumulatedTime. It represents how much time passed since the last update. So, accumulatedTime += Time.deltaTime should be performed after you call MoveTowards.
This also implies that you should limit the accumulated time. When the total time reaches or exceeds 10.0f (or whatever factor you choose), the ratio supplied to MoveTowards should be 1.0f, and the animation should stop - it reached the goal.