Reputation: 241
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).
Upvotes: 2
Views: 28479
Reputation: 10720
Here is how to use MoveTowards
:
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, PositionB, step);
}
Upvotes: 5
Reputation: 178
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.
Upvotes: 11