如何在 FixedUpdate 中移动刚体,但我的角色仍会受到重力影响?

How do I move the Rigidbody in FixedUpdate, but still have my character be affected by gravity?

所以

下面是我最初用来控制角色移动的内容。

_RigidBody.velocity = _ConstantWalkingSpeed * direction.normalized;

这适用于向 4 个方向走动。但是,如果我的角色从边缘掉下来,他会慢慢地掉下来。如果我然后在半空中禁用行走脚本,重力将以正常速度上升。

这让我相信我的移动脚本会以某种方式影响重力效果。

因此我尝试了这个解决方案:

_RigidBody.velocity = _ConstantWalkingSpeed * direction.normalized + new Vector3(0f, _RigidBody.velocity.y, 0f);

那也没用,所以我试了这个:

_RigidBody.velocity = _ConstantWalkingSpeed * direction.normalized + new Vector3(0f, _RigidBody.velocity.y, 0f) + Physics.gravity;

这确实让重力起作用了,但后来重力变得如此强大,我无法移动。

我尝试只添加 Physics.gravity 并跳过新的矢量部分,但重力仍然太强。

TL;DR

我使用的移动脚本会影响玩家向下的重力,这是不应该的。我想让他四处走动但仍然受到重力的影响。我尝试过的想法没有奏效。

请注意,我希望将重力保持在 -9.81。

希望你们能提出有效的建议 :-)

修改速度而不是设置速度。

您正在用您的输入覆盖物理引擎应用的任何速度(例如重力)。

_RigidBody.velocity += _ConstantWalkingSpeed * direction.normalized;

您可能还想将速度 X 和 Z 值设置为最大值:

Vector3 vel = _RigidBody.velocity;
vel.x = Mathf.Min(vel.x, ConstantWalkingSpeed);
vel.z = Mathf.Min(vel.z, ConstantWalkingSpeed);
_RigidBody.velocity = vel;

您可以使用 RigidBody.movePositon:

而不是设置或修改速度

这是我编写的一个快速示例脚本:

using UnityEngine;

public class simpleMoveRB : MonoBehaviour {
    public Rigidbody myBody;
    public float _constantWalkSpeed = 3.0f;

    Vector3 moveDirection = Vector3.zero;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update() {
        if (Input.GetKey(KeyCode.A))
        {
            moveDirection.x = -1.0f;
        }
        else if(Input.GetKey(KeyCode.D))
        {
            moveDirection.x = 1.0f;
        }
        else
        {
            moveDirection.x = 0.0f;
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            myBody.AddForce(Vector3.up * 500.0f);
        }
    }

    private void FixedUpdate()
    {
            myBody.MovePosition(transform.position + moveDirection * _constantWalkSpeed * Time.deltaTime);
    }
}

您可以使用此脚本处理运动,并且重力作用在您的对象上。