Similar to the Fade Function, here’s the Move one:
public IEnumerator move(GameObject obj,Vector2 targetPos, float 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(curPos, targetPos, speed*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 (gameObject, new Vector2 (0, 0),2));
In this example the gameObject is moving towards the centre with a speed of 2.
Leave a Reply