Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to set velocity of Rigidbody without changing gravity?

Discussion in 'Scripting' started by hexagonest, Jul 9, 2015.

  1. hexagonest

    hexagonest

    Joined:
    Jul 9, 2015
    Posts:
    2
    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.

    Code (Javascript):
    1. 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.

    Code (Javascript):
    1.     #pragma strict
    2.  
    3.     var speed: float;
    4.  
    5.     private var xvel: float;
    6.     private var zvel: float;
    7.     private var rb: Rigidbody;
    8.  
    9.     function Start () {
    10.         rb = GetComponent.<Rigidbody>();
    11.     }
    12.  
    13.     function FixedUpdate () {
    14.         xvel = Input.GetAxis("Horizontal");
    15.         zvel = Input.GetAxis("Vertical");
    16.         rb.velocity = Vector3(xvel * speed, rb.velocity.y, zvel * speed);
    17.     }
    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.
     
  2. hexagonest

    hexagonest

    Joined:
    Jul 9, 2015
    Posts:
    2
    Bump. please someone?
     
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195
    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:

    Code (CSharp):
    1. private Rigidbody rb;
    2. private float horizontal, vertical;
    3.  
    4. void Start() { rb = GetComponent<Rigidbody>(); }
    5.  
    6. void Update() {
    7.     horizontal = Input.GetAxis("Horizontal") * 2f;
    8.     vertical = Input.GetAxis("Vertical") * 2f;
    9.  
    10.     if (Input.GetKeyDown(KeyCode.Space))
    11.         transform.position += Vector3.up * 20f; //to test falling!
    12. }
    13.  
    14. void FixedUpdate() {
    15.     rb.velocity = new Vector3(horizontal, rb.velocity.y, vertical);
    16. }
     
    pjbaron likes this.
  4. Hecolo

    Hecolo

    Joined:
    Mar 5, 2016
    Posts:
    48
    Hi guys, sorry to give a note to this old topic, but to approve this topic for others:

    Code (CSharp):
    1. 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!
     
    pjbaron and CheekySparrow78 like this.