Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an object with vector3.MoveTowards

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).

like image 584
Ophélia Avatar asked Dec 03 '25 13:12

Ophélia


2 Answers

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.

like image 151
Koneke Avatar answered Dec 05 '25 03:12

Koneke


Here is how to use MoveTowards:

void Update()
{
    float step = speed * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, PositionB, step);
}

LearnMore

like image 41
Umair M Avatar answered Dec 05 '25 02:12

Umair M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!