他到达目标后,如何使物体移回其原始位置?

时间:2020-10-24 00:37:09

标签: c# unity3d

开始于:

StartCoroutine(ThrowObject(objToThrow.transform, primaryTarget.transform, throwSpeed));

然后:

IEnumerator ThrowObject(Transform objectToMove, Transform toPosition, float duration)
    {
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 currentPos = objectToMove.position;

            float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

            objectToMove.position = Vector3.MoveTowards(currentPos, toPosition.position, time);

            yield return null;
        }
    }

当objectToMove已达到目标(toPosition)时,我希望脚本现在执行一些操作与等待5秒或执行任何操作无关,而是先执行某些操作,然后使objectToMove返回到以相同速度抛出的原始位置。

这是我尝试过的:

IEnumerator ThrowObject(Transform objectToMove, Transform toPosition, float duration)
    {
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 currentPos = objectToMove.position;

            float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

            objectToMove.position = Vector3.MoveTowards(currentPos, toPosition.position, time);

            yield return null;
        }

        StartCoroutine(ThrowBack(objectToMove, toPosition, duration));
    }

    IEnumerator ThrowBack(Transform objectToMove, Transform toPosition, float duration)
    {
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 currentPos = objectToMove.position;

            float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

            objectToMove.position = Vector3.MoveTowards(toPosition.position, currentPos, time);

            yield return null;
        }
    }

但是它永远不会移回去。到达ThrowBack为止:

objectToMove.position = Vector3.MoveTowards(toPosition.position, currentPos, time);

但是objectToMove永远不会向后移动并保持在目标位置。

1 个答案:

答案 0 :(得分:1)

最简单的方法是在程序的开始或对象的实例化处获取开始位置,如下所示:

//Variables
private Vector3 startPos;

//Code
private void Start() //or when you want to get the position
{
    startPos = transform.position;
}

//when you want to move back to the original position do this:

  objectToMove.position = Vector3.MoveTowards(startPos);

对于您的实例,我可能会在枚举器的开头执行 start 无效。 这将设置startpos,但是startpos只有1个私有变量,因此您还需要在枚举器中声明它,以便它相对于每个objectToMove。