如何使用C#unity在特定时间段内转换精灵 [英] how to translate a sprite for a certain duration using C# unity

查看:123
本文介绍了如何使用C#unity在特定时间段内转换精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我知道如何将子画面平移到给定位置,但是如何在一段时间内将子画面平移到给定位置?

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?

推荐答案

一遍又一遍地被询问.只需在Google上进行搜索就可以找到SO的答案.

This has been asked over and over again. Simply searching on Google would have came up with an answer on SO.

这可以通过使用LerpCoroutineTime.deltaTime来完成.下面的示例将在1秒内将对象从位置A移动到位置B.您应该将当前对象的位置传递到 first 参数,并将新位置传递到 second 参数.第三参数是移动对象需要多长时间(以秒为单位).

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

这篇关于如何使用C#unity在特定时间段内转换精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆