在 Vector.Lerp Unity 5.6 中更改移动速度

Change movement speed in Vector.Lerp Unity 5.6

我在 unity 游戏中使用 Vector3.Lerp 来简单地将游戏对象从一个位置平滑地移动到另一个位置。下面是我的代码:

public class playermovement : MonoBehaviour {


    public float timeTakenDuringLerp = 2f;

    private bool _isLerping;

    private Vector3 _startPosition;
    private Vector3 _endPosition;

    private float _timeStartedLerping;

    void StartLerping(int i)
    {
        _isLerping = true;
        _timeStartedLerping = Time.time  ; // adding 1 to time.time here makes it wait for 1 sec before starting

        //We set the start position to the current position, and the finish to 10 spaces in the 'forward' direction
        _startPosition = transform.position;
        _endPosition = new Vector3(transform.position.x + i,transform.position.y,transform.position.z);

    }

    void Update()
    {
        //When the user hits the spacebar, we start lerping
        if(Input.GetKey(KeyCode.Space))
        {
            int i = 65;
            StartLerping(i);
        }
    }

    //We do the actual interpolation in FixedUpdate(), since we're dealing with a rigidbody
    void FixedUpdate()
    {
        if(_isLerping)
        {
            //We want percentage = 0.0 when Time.time = _timeStartedLerping
            //and percentage = 1.0 when Time.time = _timeStartedLerping + timeTakenDuringLerp
            //In other words, we want to know what percentage of "timeTakenDuringLerp" the value
            //"Time.time - _timeStartedLerping" is.
            float timeSinceStarted = Time.time - _timeStartedLerping;
            float percentageComplete = timeSinceStarted / timeTakenDuringLerp;

            //Perform the actual lerping.  Notice that the first two parameters will always be the same
            //throughout a single lerp-processs (ie. they won't change until we hit the space-bar again
            //to start another lerp)
            transform.position = Vector3.Lerp (_startPosition, _endPosition, percentageComplete);

            //When we've completed the lerp, we set _isLerping to false
            if(percentageComplete >= 1.0f)
            {
                _isLerping = false;
            }
        }
    }


}

代码运行良好,游戏对象在两点之间平滑移动。但到达目的地大约需要 1 秒。我想让它移动得更快。我尝试降低 float timeTakenDuringLerp 的值,但速度不受影响。我遵循了 this tutorial 并且那里的解释还说要更改 timeTakenDuringLerp 变量以改变速度,但它在这里不起作用。

有什么建议吗?

解决方法是

percentageComplete 值乘以 speed 值,例如

transform.position = Vector3.Lerp (_startPosition, _endPosition, percentageComplete*speed); 

所以当你增加 speed 时,它会更快。

H℮y,感谢您链接到我的博客!

减少timeTakenDuringLerp是正确的解决方案。这减少了对象从开始移动到结束所需的时间,这是另一种说法 "it increases the speed".

如果您希望对象以特定的速度移动,则需要将timeTakenDuringLerp设为变量而不是常量,然后进行设置至 distance/speed。或者更好的是,根本不使用 Lerp,而是设置对象的 velocity 并让 Unity 的物理引擎处理它。

按照@Thalthanas 的建议,将 percentageComplete 乘以一个常数是 不正确的 。这会导致 lerping 更新在 lerping 完成后继续发生。这也使代码难以理解,因为 timeTakenDuringLerp 不再是 lerp 期间花费的时间。

我已经仔细检查了我的代码,它确实有效,所以你遇到的问题一定是在别处。或者你不小心增加了时间,这会降低速度?