How do I move the Rigidbody in FixedUpdate, but st

2019-08-02 11:54发布

问题:

So

Below you see what I initially used to control my characters movement.

_RigidBody.velocity = _ConstantWalkingSpeed * direction.normalized;

This works for walking around in 4 directions. However, if my character falls over an edge, he falls veeeeeery slowly. If I then in mid air disable the walking script, gravity picks up and goes at normal speed.

This leads me to believe that my movement script somehow affects the gravity effect.

As such I tried this solution:

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

That didn't work either, so I tried this:

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

That did make the gravity work, but then the gravity became so strong that I can't move.

I tried only adding Physics.gravity and skipping the new vector part, but then the gravity is still too strong.

TL;DR

The movement script I use affects the players downward gravity, which it shouldn't. I want him to move around but still be affected by gravity. Ideas I have tried didn't work.

Please note that I'd prefer to keep the gravity at -9.81.

Hoping you guys have a suggestion that works :-)

回答1:

Instead of setting or modifying the velocity, You can use RigidBody.movePositon:

Here is a quick example script I wrote up:

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);
    }
}

You can handle movement using this script, and still have gravity work on your object.



回答2:

Instead of setting the velocity, modify the velocity.

You're overwriting any velocity applied by the physics engine (e.g. gravity) with your input.

_RigidBody.velocity += _ConstantWalkingSpeed * direction.normalized;

You may also want to cap the velocity X and Z values to a maximum:

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