【问题标题】:Move Object Between Two Point in X axis在 X 轴两点之间移动对象
【发布时间】:2014-03-18 23:02:43
【问题描述】:

我尝试编写使对象移动到点的代码让我们假设 ( 0 , 0 ) 和 ( 10 , 0 ) 这是我试图编写的代码,对于开发的任何建议,请不要犹豫:)。

using UnityEngine;
using System.Collections;

public class walk2 : MonoBehaviour {
    // Use this for initialization
    void Start () { }

    void Update () {
        float move = 1.00f;
        for ( int i = 0 ; i < 10 ; i++){
            transform.position = new Vector2 (transform.position.x + move, transform.position.y);
        }   

        for ( int j = 0 ; j < 10 ; j++ ){
            transform.position = new Vector2(transform.position.x - move, transform.position.y);
        }
    }
}

【问题讨论】:

  • 向本站上传问题的一个建议:请合理地格式化您的代码,空格太多了。

标签: c# loops for-loop unity3d


【解决方案1】:

我建议每次更新只进行一次移动 -

private float move = 0.1f;
void Update() {
    if (transform.position.x < 10) {    
        transform.position = new Vector2 (transform.position.x + move, transform.position.y);
    } else {
        transform.position = new Vector2 (transform.position.x - move, transform.position.y);  
    }
}

这将使对象每刻移动 0.1 个单位。我相信 Unity 每秒执行大约 50 个滴答声。话虽如此,您也可以使用Lerp 方法在两点之间进行平滑变换。

transform.position = Vector2.Lerp(starting_vector, target_vector, Time.deltaTime);

【讨论】:

  • +1 我同意。我不会完全像这样编写代码,但是如果从 Unity(blit/refresh)调用 Update,那么 let 就像 Ben 一样更新帧同步。
【解决方案2】:

更好的方法是使用transform.Translate(&lt;vector&gt;),这样使用起来更简单,而且我想效率更高。

所以你会有这样的东西,transform.Translate(new Vector3(move,0,0));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多