减速刚体

Slow down Rigidbody

我正在添加基于 GetAxis ("Vertical") 的前向力和高达 normal max speed 的速度调节器。

我还允许 "speed boost" 在正常增加的力之上增加更多的力,最高可达 boosted max speed

我遇到的困难是在加速期结束后让物体减速

所以基本上,如果您将速度提升到比正常最大速度更快的速度并且您不能再加速,请将物体减慢到正常最大速度。

这是我目前得到的:

    float velocity;
    float magnitude = myRigidBody.velocity.magnitude;
    float vertical = Input.GetAxis ("Vertical");
    if (Input.GetKeyUp(KeyCode.LeftShift)) {
        boost = false;
    }
    if (Input.GetKeyDown (KeyCode.LeftShift)) {
        boost = true;
    }
    if (!boost) {
        velocity = vertical * speed;
        Vector3 force = myRigidBody.transform.forward * velocity;
        if (magnitude + force.sqrMagnitude < normalMaxSpeed) { 
            myRigidBody.drag = 0f;
            myRigidBody.AddForce (force, ForceMode.Impulse);
        } else if (magnitude + force.sqrMagnitude >= maxTrust + 50) { 
            myRigidBody.drag = 1.5f;
        }
    } else if ( magnitude < boostedMaxSpeed) { 
        velocity = vertical * (speed + speedBoost);
        myRigidBody.AddForce (myRigidBody.transform.forward * velocity, ForceMode.Impulse);

这有些工作,但除了改变阻力之外必须有更好的解决方案。

除了改变阻力,还有其他方法可以做到这一点。您只需要试验一下,看看哪个效果最好。

1.改拖

myRigidBody.drag = 20f;

2.给相反的速度加力.

public Rigidbody myRigidBody;
void FixedUpdate()
{
    Vector3 oppositeVelocity = -myRigidBody.velocity;
    myRigidBody.AddRelativeForce(oppositeVelocity);
}

3。将当前速度递减或 Lerp 回到法向力。

public Rigidbody myRigidBody;
Vector3 normalForce;

void Start()
{
    normalForce = new Vector3(50, 0, 0);

    //Add force  
    myRigidBody.velocity = new Vector3(500f, 0f, 0f);
    //OR
    //myRigidBody.AddForce(new Vector3(500f, 0f, 0f));
}

void FixedUpdate()
{
    //Go back to normal force within 2 seconds
    slowDown(myRigidBody, normalForce, 2);
    Debug.Log(myRigidBody.velocity);
}

bool isMoving = false;

void slowDown(Rigidbody rgBody, Vector3 normalForce, float duration)
{
    if (!isMoving)
    {
        isMoving = true;
        StartCoroutine(_slowDown(rgBody, normalForce, duration));
    }
}

IEnumerator _slowDown(Rigidbody rgBody, Vector3 normalForce, float duration)
{
    float counter = 0;
    //Get the current position of the object to be moved
    Vector3 currentForce = rgBody.velocity;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        rgBody.velocity = Vector3.Lerp(currentForce, normalForce, counter / duration);
        yield return null;
    }

    isMoving = false;
}

4。改变Physics Material动摩擦。您不能使用此方法,因为它需要您没有的对撞机。

//Get the PhysicMaterial then change its dynamicFriction
PhysicMaterial pMat = myRigidBody.GetComponent<Collider>().material;
pMat.dynamicFriction = 10;

试验并决定哪一个最适合您,完全取决于您。它们的用处取决于您制作的游戏类型。例如,#4主要用于滚球,因为它使用物理material,需要经常碰撞才能真正起作用。

#3 中使用的方法让您可以控制转换发生的时间。如果你需要控制它,那就是选择。