运动取决于帧速率。我怎样才能让它独立于帧率

Movement is dependent to frame-rate. How can i make it independent from frame-rate

我对编码还很陌生。直到现在我搜索了很多东西但我仍然无法解决我的问题。我正在尝试让游戏对象跟随 line/graph。我试图给他一个负 Y 速度并添加小数字(类似;更新{mybody.velocity += 0.005})每次更新以使其移动。但我遇到了一个问题,在低帧率下,我的对象走的是一条超宽的路径,而在更高的帧率下,它走的是超窄的路径。我怎样才能让我的运动独立。

private float curve = 0;
private float curvemax = 2.3f;
[SerializeField]
private float curveupdate = 0.05f;
if (tracking.found && !hareketeBaşlandı)
        {
            curve = -(curvemax);
            triggered1 = true;
            hareketeBaşlandı = true;
            print(curve);

        }
        if (transform.position.y != y1-curvemax && tracking.found)
        {
            curve += curveupdate;

            print(curve+"Curving");
            
        }
        
        if (curve >= (curvemax))
        {

            curve = 0;
            y2 = transform.position.y;
            transform.position = new Vector3(transform.position.x, y1, transform.position.z);
            tracking.found = false;
            tracking.shouldsearch = false;
            StartCoroutine("trackCD");
            print("track off");
            myBody.velocity = new Vector2(myBody.velocity.x, curve);
            hareketeBaşlandı = false;

        }

与其考虑“变化率”,不如考虑“每单位时间的变化率”。

例如,您似乎正在根据 curveupdate = 0.05f; 更新 curve,它的变化率为 0.05f。您需要考虑每秒 的变化率。假设您当前每帧获得 0.05f 变化,假设每秒 10 帧,这意味着您的每秒变化率是每秒 0.5f(高十倍)。

然后您应用此数量乘以经过的秒数。方法如下。

首先当你启动动画时,你需要记住它是什么时候开始的:

var lastUpdateTime = DateTime.Now;

然后改变这个:

curve += curveupdate;

为此:

DateTime currentTime = DateTime.Now;
float secondsElapsed = (float)(currentTime - lastUpdateTime).TotalMilliseconds / 1000F;
curve += (curveupdate * secondsElaped);
lastUpdateTime = currentTime;

这样一来,变化量就会随着时间的推移而变化。如果没有时间过去,它会一直缩小到 0,如果时间过去了,它最终会变得非常非常大。因此,对于最终用户来说,变化率应该随着时间的推移保持一致。

请注意,在 中使用 DateTime.NowTimeSpan 计算非常昂贵......特别是如果你使用它 每帧 只是为了以秒为单位计算增量。

这实际上正是 Unity 在 Time.deltaTime 中已经提供的内容,自上次渲染后经过的时间(以秒为单位).. 如果我们已经知道该值,为什么还要计算复杂的 ;)

curve += curveupdate * Time.deltaTime;

简单来说,乘以 Time.deltaTime 会将任何值从“每帧值”转换为与帧速率无关的“每秒值”