Reusable Move Function in Unity

Posted on

in

,

Similar to the Fade Function, here’s the Move one:

public IEnumerator move(GameObject obj,Vector2 targetPosfloat speed = 1){

        Vector2 startingPos = obj.transform.position;

        while(startingPos.x != targetPos.x || startingPos.y != targetPos.y){
            Vector2 curPos = obj.transform.position;
            if(curPos == targetPos){
                yield break;    
            }
            obj.transform.position = Vector2.MoveTowards(curPostargetPosspeed*Time.deltaTime);
            print ("moving "+curPos +" - "+targetPos );
            yield return null;
        }
    }

This function assumes you’re moving a game object from it’s current position to another. It’s parameters are the GameObject, the position it wants to move to and a speed that’s set to 1 by default.

An example of using it:

StartCoroutine (move (gameObjectnew Vector2 (0, 0),2));

In this example the gameObject is moving towards the centre with a speed of 2.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

June 2024
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930