【问题标题】:How should I calculate the speed of a Lerp?我应该如何计算 Lerp 的速度?
【发布时间】:2021-03-30 01:28:38
【问题描述】:

我有一个 Vector2 Lerp 语句:

Vector2.Lerp(spawnPos, target, position);

position 变量是一个介于 0 和 1 之间的数字,出于所有意图和目的,它会随时间递增。想想我将position 跟踪为“播放头”的方式,就像在音乐或动画中一样,随着播放的继续,光标会从左向右移动。

我希望对象在到达目标后继续移动,以相同的精确速度,只是无限地朝一个方向移动。我尝试将目标更改为乘以生成点之间的距离的方向,但我仍然无法弄清楚如何获得正确的速度。

【问题讨论】:

  • 在现实世界中,速度=距离/时间。如果你知道你走了多远,走了多长时间,那么你就知道了速度。如果您知道平均帧速率以及每帧 position 的变化量,您可能无需记录即可估算时间。
  • @Llama 非常感谢!这正是我所需要的,我很快就会写一个答案:)

标签: c# unity3d


【解决方案1】:

给你一个稍微简单的答案:不要使用 Vector2.Lerp 并计算所有内容,只需使用 Vector2.LerpUnclamped 并输入任何你想要的 t 值!

【讨论】:

  • 哦,是的,这是一个很好的解决方案。我试试看!
  • 这太完美了,非常感谢!标记为正确,因为它是最简单和最有效的答案:)
【解决方案2】:

感谢Llama 的评论,我能够计算出 Lerp 的速度。

首先,记录插值的开始和结束时间,以及插值是否完成(position >= 1)。然后,如果它还没有完成,像往常一样 lerp。如果它已经完成,请记下结束时间,计算移动的速度和方向,并将 Transform.position 增加该值。

bool finished = false;

// Since I'm using AudioSettings.dspTime, I need to use double.
// Most forms of telling time in Unity will use float
double startTime;
double endTime;

void Start()
{
    // This is what I am using for my game, 
    // but you can use any way of telling time that Unity/C# provides.
    startTime = AudioSettings.dspTime;
}

void Update()
{
    if(!finished)
    {
        // interpolate
        transform.position = Vector2.Lerp(spawnPos, targetPos, position);
        if(position >= 1)
        {
            // Record our end time
            endTime = AudioSettings.dspTime;
            finished = true
        }
    } else {
        // How long it took to lerp
        double lerpTime = endTime - startTime;
        // How far we lerped
        float distance = Vector2.Distance(spawnPos, targetPos);
        // The speed to further move
        float speed = distance / (float)lerpTime;
        // The direction in which to move
        Vector2 direction = (targetPos - spawnPos).normalized;

        // Continue moving
        transform.position += (Vector3)direction * speed * Time.deltaTime;
    }
}

【讨论】:

  • position 来自哪里?
  • @derHugo 位置基于AudioSettings.dspTime、“播放”位置和未来时间
  • 好吧,这既不在您的问题中,也不在您的答案代码中……我的问题的原因是:随着时间的推移,谁在增加position .. 那不是已经告诉你了吗增加它需要多长时间 => 已经可以告诉您 position 的增长速度有多快 => 已经可以告诉您正在寻找的速度值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多