How To Do Vector MoveTowards – Unity C#

A common task is moving one object towards another position in Unity. Assuming you want constant, linear speed, Vector.MoveTowards is a great solution. You can also do lerping covered in this article here.

Move Towards

The psuedocode is:

Object to moveMoveTowards( currentPosition, endPosition, speed);

Example code:

piece.transform.position = Vector3.MoveTowards(piece.transform.position, end, speed * Time.deltaTime);

It says, move the object from it’s current position towards the end position at the following speed.

current position  is not the objects starting position, but its position each frame, because each frame it checks the current position and moves it closer towards the end position.

endPosition is simply where want your object to finish moving.

Speed is the speed to move. We multiply speed by deltaTime because, if speed was 1, we would be saying, “We want this object to take one second to move”. Multiplying the speed by delta time makes sure that movement is divided up evenly across the update frames. Increase the speed and the object will move faster.

Example code:

public GameObject block;

void Update ()
 { 
    if (Input.GetKeyDown(KeyCode.Space))
    { 
        StartCoroutine(MovePieceTowards(block, block.transform.position + new Vector3(10, 0, 0), 10)); 
    }
 }

 IEnumerator MovePieceTowards(GameObject piece, Vector3 end, float speed)
 {
    while (piece.transform.position != end)
    {
        piece.transform.position = Vector3.MoveTowards(piece.transform.position, end, speed * Time.deltaTime);
        yield return null;
    }
 }

We have a public game object called block. Pass any object you like in the inspector.

On Update, we start a Coroutine when we press the Space key. We pass the block game object in, we set it’s end destination, and we set the speed. Currently it will move 10  units to the right.

The co-routine keeps running until the object has finished moving. We return null because co-routines have to return a value. Try it out.

Conclusion

Thanks for reading. I update this blog whenever I feel like I have something useful to share in regards to game development, either in game design, programming, or something about my current game projects. Follow the blog if you’d like further updates and tutorials.

If you are still a bit unsure about MoveTowards, try looking at the Unity documentation:

Documentation MoveTowards

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s