0

这个问题有两个部分 - 第一个是运行嵌套的 for 循环以通过它们的碰撞边界(collider.bounds)分隔父游戏对象的子对象。如果发生碰撞(边界相交),相交的游戏对象会执行 Lerp 代码以尝试退出碰撞。

Lerp 执行正常,但如图所示,它运行不正常。它将孩子 1,2,3,4 正确地移动到彼此边界之外,但它将它们完全移离孩子 0 太远。同样,如果持续时间改变,移动每个对象的时间也会调整,但它们之间的距离也会调整他们——不应该这样。

编辑:(附加细节)
函数通过参数而不是 Transform 和 Vector3 传递索引。Transform fromPosition、Vector3 toPosition 和 startPos 都以相同的方式使用,但是,而不是像 Programmers coroutine 最初那样传递它们(因为我不能,因为这个实现是特定于运行时的,我不知道哪些对象确切地说,这将在上面运行)它们是在修改后的协同程序中首先计算出来的。

程序员的实现是将游戏对象移动到指定位置。我需要对每个孩子进行 Lerp 直到他们不与彼此的界限相交。

这意味着 Lerp 需要按照 endPosition 的规范持续执行,一旦其移动的对象不再与其比较的对象相交。这里实现的方式是使用一个while循环来不断地执行一个渐进运动的Lerp(Vector3.right)作为endPosition,直到碰撞体不再相交。问题是,它没有按预期工作。

那么,如何在这里修复 Lerp 实现呢?

下面的资源:
内嵌图片,该图片的链接,相关代码

PS:

  • 注释'//translating'下的代码是为了显示想要的结果是什么,除了翻译不会像Lerp那样产生平滑的运动。
  • 协程“MoveToX”几乎完全是从 SE 上的一个类似问题中重用的代码,其中用户询问如何在更新之外顺利进行 Lerp。

外部图片链接

内联图二

int numChildren = gameObject.transform.childCount;
for (int i = 0; i<numChildren; i++)
{
    for (int a = i+1; a<numChildren; a++)
    {
        while (gameObject.transform.GetChild(a).GetComponentInChildren<Collider>().bounds.Intersects
            (gameObject.transform.GetChild(i).GetComponentInChildren<Collider>().bounds))
        {
            // print
            Debug.Log("Bounds intersecting " + i + ":" + a);

            // translating
            //gameObject.transform.GetChild(a).GetComponentInChildren<Transform>()
            //    .transform.Translate(Vector3.right* Time.deltaTime* 100f, Space.World);

            // lerping
            StartCoroutine(MoveToX(a, 0.1f));

        }
    }
}


IEnumerator MoveToX(int a, float duration)
{
    //Get the current position of the object to be moved
    Vector3 startPos = gameObject.transform.GetChild(a).transform.position;

    Vector3 toPosition = gameObject.transform.GetChild(a).transform.position + Vector3.right;

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

    while (counter < duration)
    {
        counter += Time.deltaTime;
        gameObject.transform.GetChild(a).transform.position = Vector3.Lerp(startPos, toPosition, counter / duration);
        yield return null;
    }

    isMoving = false;
}
4

0 回答 0