【问题标题】:Movement Loop in UnityUnity 中的运动循环
【发布时间】:2023-03-18 06:08:02
【问题描述】:

我有 4 个对象,每个对象都位于正方形的一个角落。我希望顺时针移动这些对象,每个方法调用 1 个位置。

使用我的 atm 代码,它们都只是在 1 个方法调用上完成整个循环,而不是只移动一个位置...

到目前为止我的代码:

void SwitchPositions() 
    {

            tempPosition1 = parent.transform.GetChild(0).GetComponent<Transform>().position;
            tempPosition2 = parent.transform.GetChild(1).GetComponent<Transform>().position;
            tempPosition3 = parent.transform.GetChild(2).GetComponent<Transform>().position;
            tempPosition4 = parent.transform.GetChild(3).GetComponent<Transform>().position;
            parent.transform.GetChild (0).GetComponent<Transform> ().position = tempPosition2;
            parent.transform.GetChild (1).GetComponent<Transform> ().position = tempPosition3;
            parent.transform.GetChild (2).GetComponent<Transform> ().position = tempPosition4;
            parent.transform.GetChild (3).GetComponent<Transform> ().position = tempPosition1;
            Debug.Log (tempPosition1);


    }

如果有人对如何解决这个问题有任何想法,或者至少向我解释一下为什么它会在 1 个方法调用中完成整个循环......

谢谢!

【问题讨论】:

  • 这叫什么? (这段代码调用了多少次)
  • 有一个定时器,2秒。方法完成后它会重置。计时器倒计时使用 -= Time.deltaTime @Sayse
  • 那么它被调用了多少次?代码本身看起来不像问题(对我来说),看起来更像是它被多次调用,要么所有 4 个对象都在执行此代码,要么该计时器执行了太多次
  • @Sayse 代码应该永远循环,至少这就是整个想法。我想每 2 秒更改一次对象的位置。他们应该永远改变立场。
  • 很好,应该可以,我想你需要看看计时器,我对统一不太熟悉,但我相信它有自己的游戏循环,你应该看看与之交互而不是创建一个单独的计时器。 (跟踪自调用此方法以来的最后一次时间,仅在大于 2 秒时调用)

标签: c# unity3d


【解决方案1】:

我真的不确定你的计时器是如何工作的,或者你的代码有什么问题。但是我使用了协程,每两秒钟后块就会切换一次,并且它会连续发生。我认为这应该接近您的需求。

//Predefined positions where objects to place
public Transform[] Position;
//The objects that will will be swapped in coroutines
public Transform[] ObjectsToMove;
private int ObjectIndex = 0;
private bool startupdate = true;

void Update () {
    if(startupdate)
       StartCoroutine(SwitchBlocks());
}

IEnumerator SwitchBlocks() {
    startupdate = false;
    int tempIndex = ObjectIndex;
    for(int i = 0; i < ObjectsToMove.Length; i++) {
        tempIndex = ObjectIndex + i;
        if(tempIndex > ObjectsToMove.Length - 1)
            tempIndex -= ObjectsToMove.Length;
        ObjectsToMove[i].position = Position[tempIndex].position;
    }
    ObjectIndex++;
    if(ObjectIndex > ObjectsToMove.Length - 1) {
        ObjectIndex = 0;
    }
    yield return new WaitForSeconds(2.0f);
    startupdate = true;
    yield return null;
}

希望这会有所帮助。

【讨论】:

  • 不起作用...完全相同...对不起,谢谢。
  • 会不会是它执行 4 次导致 4 个核心?
  • 在这一点上,我不能说为什么你的代码执行了四次,除非我看到我不能说的整个代码,而且我认为它不会因为四个内核而被执行。我想到的只有两件事,一是您的计时器功能可能不正确,因此它会像那样执行,或者同时从其他地方调用 SwitchPositions()。如果您能够发布执行此函数的计时器代码,我们也许可以解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多