how to translate a sprite for a certain duration using C# unity [duplicate]

烂漫一生 提交于 2019-12-13 02:37:05

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/37517114/how-to-translate-a-sprite-for-a-certain-duration-using-c-sharp-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!