如何从位置A到B在x秒[重复]

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

这个问题在这里已有答案:

基本上我的代码工作正常,一切都很好。我唯一的问题是角色正在改变位置是这条线的秒数

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个回答
0
投票

由于您只更改了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);
    }
}

如果有错误(我是在没有测试的情况下从头部完成的),告诉我它是什么,我会纠正它。

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