Unity - 将多个游戏对象从当前位置移动(随机播放)到新的目标位置

Unity - Move (Shuffle) multiple GameObject from their current position to a new destination position

我正在尝试执行随机播放功能,以便我可以更改多个 GameObjects 的顺序。

我在一个圆圈中有多个 "letters" (GameObjects),当我单击 "Shuffle" 时,我只需要重新排序它们的位置,但显示字母移动到它的新位置。

我试过了:Vector3.Lerp(startPosition, targetPosition, Time.time/2)

Vector3.MoveTowards(startPosition, targetPosition, Time.time/2)

但它没有正确移动。

我设法用这个做动作:

Vector3 tempPosition = object1.transform.position; object1.transform.position = object2.transform.position; object2.transform.position = tempPosition;

但是我只能移动2GameObjects,没有任何动作。

获取所有字母的列表,使用协程移动字母,并在协程的开始,找出每个字母从哪里移动到哪里,然后在每一帧中使用lerp设置位置:

public float letterMoveTime = 1f; // duration of shuffle movement (in seconds)
List<GameObject> letters;
IEnumerator shuffleCoroutine;

void Awake()
{
    letters = new List<GameOobject>();
    letters.AddRange(GameObject.FindGameObjectsWithTag("Letter"));

    shuffleCoroutine = null;
}

public void StartShuffle() // call this on button click
{
    if (shuffleCoroutine != null) return;

    shuffleCoroutine = DoShuffle();
    StartCoroutine(shuffleCoroutine);
}

IEnumerator DoShuffle()
{
    List<Vector3> startPos = new List<Vector3>();
    List<Vector3> endPos = new List<Vector3>();
    foreach (GameObject letter in letters)
    {
        startPos.Add(letter.transform.position);
        endPos.Add(letter.transform.position);
    }

    // shuffle endPos
    for (int i = 0 ; i < endPos.Count ; i++) {
         Vector3 temp = endPos[i];
         int swapIndex = Random.Range(i, endPos.Count);
         endPos[i] = endPos[swapIndex];
         endPos[swapIndex] = temp;
     }

     float elapsedTime = 0f;

     while (elapsedTime < letterMoveTime)
     {
         // wait for next frame
         yield return null;

         // move each letter
         elapsedTime  = Mathf.Min(letterMoveTime, elapsedTime+Time.deltaTime);
         float t = elapsedTime / letterMoveTime;

         for (int i = 0 ; i < startPos.Count ; i++) {
             letter[i].transform.position = Vector3.lerp(startPos[i],endPos[i],t);
         }
     }

     // allow shuffling to occur again
     shuffleCoroutine = null;
}