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

问题描述 投票:1回答:2

我在团结游戏中使用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变量以便改变速度但它在这里不起作用。

有什么建议吗?

unity3d unityscript lerp
2个回答
2
投票

℮,谢谢你链接到我的博客!

减少timeTakenDuringLerp是正确的解决方案。这减少了物体从开始到结束所需的时间,这是另一种说法“它会提高速度”。

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

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

我已经对我的代码进行了双重检查,确实有效,因此您遇到的问题必须在其他地方。或者也许你不小心增加了时间,这会降低速度?


0
投票

解决方案是

percentageComplete值乘以speed值,如,

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

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

© www.soinside.com 2019 - 2024. All rights reserved.