如何使用 C# unity 在一定时间内翻译精灵
how to translate a sprite for a certain duration using C# unity
通常我知道如何将精灵平移到给定位置,但如何在一段时间内将精灵平移到给定位置?
这个问题已经被 反复询问过。简单地搜索 Google 就会得出关于 SO 的答案。
这可以通过使用 Lerp
、Coroutine
和 Time.deltaTime
来完成。下面的示例将在 1 秒内将对象从位置 A 移动到 B。您应该将当前对象的位置传递给 first 参数和要移动到的新位置,在 second parameter.The 第三个参数是移动对象需要多长时间(以秒为单位)。
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;
}
通常我知道如何将精灵平移到给定位置,但如何在一段时间内将精灵平移到给定位置?
这个问题已经被
这可以通过使用 Lerp
、Coroutine
和 Time.deltaTime
来完成。下面的示例将在 1 秒内将对象从位置 A 移动到 B。您应该将当前对象的位置传递给 first 参数和要移动到的新位置,在 second parameter.The 第三个参数是移动对象需要多长时间(以秒为单位)。
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;
}