Generally I know how to translate a sprite to a given position, but how can I translate a sprite to a given position over a time period?
Asked
Active
Viewed 508 times
1 Answers
2
This has been asked over and over again. Simply searching on Google would have came up with an answer on SO.
This can be done with the use of Lerp
, Coroutine
and Time.deltaTime
. The example below will move the Object from postion A to B within 1 second. You should pass in the current Object's position to the first parameter and the new position to move to, in the second parameter.The third parameter is how long(in seconds) it will take to move the Object.
public GameObject objectectA;
public GameObject objectectB;
void Start()
{
StartCoroutine(moveToPos(objectectA.transform, objectectB.transform.position, 1.0f));
}
bool isMoving = false;
IEnumerator moveToPos(Transform fromPosition, Vector3 toPosition, float duration)
{
//Make sure there is only one instance of this function running
if (isMoving)
{
yield break; ///exit if this is still running
}
isMoving = true;
float counter = 0;
//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
isMoving = false;
}

Community
- 1
- 1

Programmer
- 121,791
- 22
- 236
- 328