【问题标题】:Unity3d: Trying to move an object forwards then backwardUnity3d:尝试将对象向前移动然后向后移动
【发布时间】:2018-09-15 20:39:49
【问题描述】:

我是 Unity 的新手,正在尝试找到一种方法将块向前移动一段固定的时间,然后让它在同样的时间内返回到其起始位置。我正在使用 Time.deltaTime 来移动块一段时间,这确实有效。但是,一旦 countDown 变量达到 0 并且对象必须开始返回其原始位置,对象就会停止移动,我不知道为什么。

public class Problem1 : MonoBehaviour { 
    float countDown = 5.0f;

    // Use this for initialization
    void Start () {

    }

    void Update () {
        transform.position += Vector3.forward * Time.deltaTime;
        countDown -= Time.deltaTime;

        if (countDown <= 0.0f)
            transform.position += Vector3.back * Time.deltaTime;
 }
}

我相当肯定我使用 Vector3.back 不正确,但我不知道怎么做。

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    这是因为您同时向前和向后移动对象。 当countDown 大于 0 时,您只想将其向前移动。
    这是您需要的代码:

    public class Problem1 : MonoBehaviour { 
        float countDown = 5.0f;
    
        // Use this for initialization
        void Start () {
    
        }
    
        void Update () {
            countDown -= Time.deltaTime;
    
            if(countDown > 0)
                transform.position += Vector3.forward * Time.deltaTime;
            else if (countDown > -5.0f) // You don't want to move backwards too much!
                transform.position += Vector3.back * Time.deltaTime;
     }
    }
    

    【讨论】:

      【解决方案2】:

      对象停止移动,因为一旦 countDown 达到 0.0f,您仍在向前移动它,但您也在向后移动它。

      换句话说,您运行的代码基本上是这样做的:

      if (countDown > 0.0f) {
          transform.position += Vector3.forward * Time.deltaTime;
          countDown -= Time.deltaTime;
      } else if (countDown <= 0.0f) {
          transform.position += Vector3.forward * Time.deltaTime;
          transform.position += Vector3.back * Time.deltaTime;
          countDown -= Time.deltaTime;
      

      我建议您像这样运行您的代码:

      public class Problem1 : MonoBehaviour { 
      float countDown = 5.0f;
      
      // Use this for initialization
      void Start () {
      
      }
      
      void Update () {
          if (countDown > 0.0f) {
          transform.position += Vector3.forward * Time.deltaTime;
          countDown -= Time.deltaTime;
      }
      
          else if (countDown <= 0.0f) {
              transform.position += Vector3.back * Time.deltaTime;
          countDown += Time.deltaTime;
          }
      }
      }
      

      事实上,else 语句在 else if 语句所在的地方可能会更好,但为了清楚起见,我将它设置为 else if 语句。

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-27
        • 2019-03-09
        相关资源
        最近更新 更多