如何在Unity中计算GameObject的速度?

时间:2019-03-07 11:44:19

标签: unity3d

我尝试过

float speed = (currentPosition - previousPosition).magnitude / Time.deltaTime

Update()

但是我得到非常不好的结果,因为currentPositionpreviousPosition太近了。减法后舍入误差太大。速度值波动太大。

而且我也不想在多个帧之间求平均值,因为这会产生延迟,并且只会稍微改善结果。

有没有更好的方法来计算物体的速度?

1 个答案:

答案 0 :(得分:1)

您可以使用协程来计算比每帧都要慢的速度:

void OnEnabled() {
    StartCoroutine(SpeedReckoner());
}

public float Speed;
public float UpdateDelay;

private IEnumerator SpeedReckoner() {

    YieldInstruction timedWait = new WaitForSeconds(UpdateDelay);
    Vector3 lastPosition = transform.position;
    float lastTimestamp = Time.time;

    while (enabled) {
        yield return timedWait;

        var deltaPosition = (transform.position - lastPosition).magnitude;
        var deltaTime = Time.time - lastTimestamp;

        if (Mathf.Approximately(deltaPosition, 0f)) // Clean up "near-zero" displacement
            deltaPosition = 0f;

        Speed = deltaPosition / deltaTime;


        lastPosition = transform.position;
        lastTimestamp = Time.time;
    }
}