c# - 在Unity中动态改变物体的速度

标签 c# unity3d

我需要一个根据动态时间上下移动的对象。确切位置存储在名为 Timings 的 List() 中。这将包含排序的条目,例如 0.90 1.895 2.64 3.98... 这些时间与音乐播放有关,因此可以将它们与 TheMusic.time 进行比较。 (TheMusic 是我的音频源)。

现在(见下面的代码),它正在使用 moveSpeed 静态地上下移动。我怎样才能做到这一点,或者在预定义的时间达到最高点和最低点?当它到达计时列表的末尾时,运动应该停止。

public class Patrol : MonoBehaviour {

    public Transform[] patrolPoints;  //contains top and bottom position
    public float moveSpeed; //needs to be changed dynamically

    private int currentPoint; 

    // Initialization
    void Start () {
        transform.position = patrolPoints [0].position;
        currentPoint = 0;
    }

    // Update is called once per frame
    void Update () {

        print (currentPoint);
        if (currentPoint >= patrolPoints.Length) {
            currentPoint = 0;
        }

        if (transform.position == patrolPoints [currentPoint].position) {
            currentPoint++;
        }

        transform.position = Vector3.MoveTowards (transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);

    }
}

重要的是没有离开绝对时间点。例如。当 Timings 达到 1009 之类的高时间时,应该不会有太大的漂移。

另请注意,其他事情(例如更改颜色和检查用户行为)需要同时发生,请参阅我的 other question .

最佳答案

添加一个 float 组让我们说 public float[] moveSpeedArray;

您可以根据需要在 Start() 或编辑器中填充此数组。

您已经获取了 currentPoint 并更新了它。

currentPoint 作为您的 moveSpeedArray 的索引。

喜欢;

transform.position = Vector3.MoveTowards (transform.position, patrolPoints[currentPoint].position, moveSpeedArray[currentPoint] * Time.deltaTime);

因此,您可以像这样在不同的预定义时间将对象移动到不同的位置。

希望对您有所帮助!干杯!

关于c# - 在Unity中动态改变物体的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318281/

相关文章:

c# - 使变量的值 A = B unity

c# - 为 64 位操作系统包装 32 位 dll 以与 regsvr32.exe 一起使用

c# - 在 C# 中展平序列化 XML

c# - 什么是 C# 等同于 C++ 句柄

c# - 长到小数点,小数点在特定位置

c# - 通过 TempData 传递 ViewModel?

javascript - 在语音气泡Unity 2D中渲染文本

unity3d - 在 Unity 中停用游戏对象后如何重置动画?

3d - 将 Unity 转换转换为 THREE.js 旋转

c# - 当 GameObject 触发时在 Unity 控制台中打印消息? Unity5/2D