【问题标题】:How to go from position A to B in x second [duplicate]如何在 x 秒内从位置 A 到 B [重复]
【发布时间】:2018-03-03 09:59:37
【问题描述】:

基本上我的代码运行良好,一切都很好。我唯一的问题是角色正在改变位置是从这一行开始的几秒钟

float perc = currentLerpTime / lerpTime;
        var _CurrentPosition = gameObject.transform.position.x;
        var DesiredPosition = Mathf.Lerp (_CurrentPosition, _CurrentPosition + evadeForce, perc);
        gameObject.transform.position = new Vector2 (DesiredPosition, gameObject.transform.position.y);

上面的代码获取当前位置然后 lerps 到新位置然后应用它。但它发生得太快了,就像玩家正在消失一样。相反,我希望它慢一点。

基本上不是在 0.1 秒内从 A 到 B,我希望它在 1 秒内从 A 到 B。

这里是完整的代码:

IEnumerator _EvadeAttacks() 
{
    Physics2D.IgnoreLayerCollision(playerLayer, EnemyLayer, true);
    currentLerpTime = 0f;
    currentLerpTime += Time.deltaTime;
    if (currentLerpTime > lerpTime) {
        currentLerpTime = lerpTime;
}
    if (!evadeLeft) 
    {
        Debug.Log ("workingright");
        float perc = currentLerpTime / lerpTime;
        var _CurrentPosition = gameObject.transform.position.x;
        var DesiredPosition = Mathf.Lerp (_CurrentPosition, _CurrentPosition + evadeForce, perc);
        gameObject.transform.position = new Vector2 (DesiredPosition, gameObject.transform.position.y);
        hasEvaded = true;
    } else if (evadeLeft) 
    {
        Debug.Log ("workingleft");
        float perc = currentLerpTime / lerpTime;
        var _CurrentPosition = gameObject.transform.position.x;
        var DesiredPosition = Mathf.Lerp (_CurrentPosition, _CurrentPosition - evadeForce, perc);
        gameObject.transform.position = new Vector2 (DesiredPosition, gameObject.transform.position.y);
        hasEvaded = true;
    }
    canWalk = true;
    yield return new WaitForSeconds(SecondsToWaitForEvadeCollider);
    Physics2D.IgnoreLayerCollision(playerLayer, EnemyLayer, false);
    yield return new WaitForSeconds (SecondsToWaitForEvadeReset);
    hasEvaded = false;
}

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    由于您仅更改 X,因此我将为仅 X 更改创建函数。如果你想改变两者,只需修改它。

    public void MoveGameObject(GameObject go, double Y,  double currentX, double desiredX, double moveSpeed)
    {
        double K = moveSpeed * 0.1; //Try different moveSpeed for effect
        double D = (desiredX - currentX) / K;
        double X = currentX;
    
        for(int I = 0; I < K; I++)
        {
            X += D;
            go.transform.position = new Vector2 (X, Y);
        }
    }
    

    如果有错误(我没有测试就直接做了),告诉我是什么,我会改正的。

    【讨论】:

    • 我会试试这个解决方案,看看它是否有效
    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2012-11-15
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多