繁体   English   中英

如何在 Unity 3D 中使用 AddForce 和 ForceMode.VelocityChange 来限制速度

[英]How to cap velocity in Unity 3D using AddForce with ForceMode.VelocityChange

我正在研究玩家 controller 并且无法限制角色的速度。 角色似乎无限加速。

我正在使用rb.AddForce(movement * movementSpeed, ForceMode.VelocityChange)更新角色的速度,其中movement是归一化的Vector3 (仅具有xz的值),而movementSpeed速度是提供所需运动速度的公共浮点数。 我意识到通过直接设置来限制角色的速度是微不足道的,但我的印象是直接设置rb.velocity是不好的做法(我不完全确定这是真的)。

我的固定更新 function:

private void FixedUpdate()
{
    Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    movement.Normalize();
    rb.AddForce(movement * movementForce, ForceMode.VelocityChange);
}

我尝试添加一个条件语句,检查速度是否大于所需的最大值,如果为真,则在相反方向添加一个力。 这会导致口吃。 角色的速度被重置为 0 并被迫再次加速。

    Vector3 currMovement = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
    float currMagnitude = currMovement.magnitude;
    if (currMagnitude > movementSpeed) {
        rb.AddForce(currMovement * (-1 * movementSpeed / currMagnitude), ForceMode.VelocityChange);
    }

任何帮助将不胜感激?

TL;博士

  • 使用rb.AddForce(movement, ForceMode.VelocityChange)时如何限制速度?
  • 我什至需要使用rb.AddForce还是可以直接设置rb.velocity

我认为直接设置速度没有任何问题,尤其是在限制速度方面。 我认为当人们在一个方向上增加一个力而不是直接设置它时,他们倾向于更好地可视化速度,但不,简而言之,我不认为这是不好的做法。

查看 Unity 的Mathf.Clamp文档。 我会做类似的事情:

private void FixedUpdate()
{
    Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    movement.Normalize();
    rb.AddForce(movement * movementForce, ForceMode.VelocityChange);
    rb.velocity = new Vector3(Mathf.Clamp(rb.velocity.x, -SomeMaximumVelocity, SomeMaximumVelocity), 
                              rb.velocity.y, 
                              Mathf.Clamp(rb.velocity.z, -SomeMaximumVelocity, SomeMaximumVelocity));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM