Moving an object with vector3.MoveTowards

Ophélia picture Ophélia · Nov 8, 2016 · Viewed 11.9k times · Source

I am working on a game app with Unity. I have an issue when it comes to move a GameObject .

In my game, when the player swipes up with his device, the GameObject moves from a point A to B, and when he swipes down, it goes from B to A.

I wrote a C# script with the game logic, but I have an issue when it comes to this.

The problem is that the GameObject moves instantly from A to B.

Here is the code line I use to move my GameObject :

transform.localPosition = Vector3.MoveTowards (PositionA,PositionB,Time.deltaTime * speed);

speed is a float with a value of 10.0f.

I would like my GameObject to move slowly to point A to B. And despite the changes on speed value, nothing change, it's still moving instantly.

How can I fix that? (I tried with Vector3.Lerp and I had the same results).

Answer

Koneke picture Koneke · Nov 8, 2016

Vector3.MoveTowards takes the current position, the target position, and the step, but it seems like your first argument here is origin of the move, rather than current position. Normally you'd do this something like this, in your Update():

transform.localPosition = Vector3.MoveTowards (transform.localPosition, PositionB, Time.deltaTime * speed);

with the current position as the first argument.