How to set velocity of Rigidbody without changing gravity?

I feel as if this shouldn’t be happening. But when I set the velocity of my rigidbody using a Vector3 like the following code is showing, it somehow messes up the gravity and the cube object starts floating down really slowly.

rb.velocity = Vector3(xmove, rb.velocity.y, zmove);

Surely this shouldn’t change the vertical velocity of the Ridgidbody at all, but it still does.

    #pragma strict
  
    var speed: float;
  
    private var xvel: float;
    private var zvel: float;
    private var rb: Rigidbody;
  
    function Start () {
        rb = GetComponent.<Rigidbody>();
    }
  
    function FixedUpdate () {
        xvel = Input.GetAxis("Horizontal");
        zvel = Input.GetAxis("Vertical");
        rb.velocity = Vector3(xvel * speed, rb.velocity.y, zvel * speed);
    }

That’s the full code attached to the player.

The reason I’m not using forces is because I want the player to be more responsive in its movement.

Bump. please someone?

That should work.

I mean, you should be getting the Horizontal and Vertical axes in Update rather than FixedUpdate, as that’s where the Input updates, but the gravity stuff should work fine.

This test setup makes a cube fall like it should:

private Rigidbody rb;
private float horizontal, vertical;

void Start() { rb = GetComponent<Rigidbody>(); }

void Update() {
    horizontal = Input.GetAxis("Horizontal") * 2f;
    vertical = Input.GetAxis("Vertical") * 2f;

    if (Input.GetKeyDown(KeyCode.Space))
        transform.position += Vector3.up * 20f; //to test falling!
}

void FixedUpdate() {
    rb.velocity = new Vector3(horizontal, rb.velocity.y, vertical);
}
1 Like

Hi guys, sorry to give a note to this old topic, but to approve this topic for others:

RG.velocity = new Vector3(MoveVector.x, RG.velocity.y, MoveVector.z);

It’s working! You add velocity and keep Gravity so your character is falling!

2 Likes