

It normalises the difference vector, giving us a unit vector that points in the same direction as the difference vector. Hence, only target.position - transform.position can work. The difference vector is back, except this time, it has to be pointing towards the target. Transform.position += difference.normalized * moveSpeed * ltaTime Vector2 difference = target.position - transform.position
#LENGTH OF A VECTOR 2D HOW TO#
Here’s how to do it if you do the vector math yourself - the code below gives almost the same result.

moveSpeed, of course, should be the distance your object can travel in 1 second. This will move your object’s position by moveSpeed * ltaTime units at every frame until it reaches its destination. transform.position = Vector2.MoveTowards( transform.position, target.position, moveSpeed * ltaTime ) You have to declare it as a property of your script and assign it to make it work.

In the script below, target is the Transform component of the target you are following, assigned to the same script. To move an object towards a target at a particular speed (expressed by moveSpeed in the snippet below), you can use the following line using Vector2.MoveTowards() in your script’s Update() method.
