Search Unity

Question about Velocity

Discussion in 'Scripting' started by PajamaJohn, Jun 14, 2018.

  1. PajamaJohn

    PajamaJohn

    Joined:
    Dec 2, 2017
    Posts:
    20
    Hello,

    Can someone please explain to me why I could not use rb.velocity twice in my code. When I run my game, the player object cannot jump due to movement using rb.velocity. When I change movement to MovePosition or AddForce, it works fine. I’m just curious to why it wouldn’t work if I used rb.velocity for both Jump and movement.

    Here is my code.
    Code (CSharp):
    1. public float jumpForce;  //set jump's strength.
    2. public float speed;  //how fast the object move.
    3.  
    4. private Rigidbody rb;  //store rigidbody component
    5.  
    6. void Start ()
    7.     {
    8.         rb = GetComponent<Rigidbody>();  //Get Rigidbody component  
    9.     }
    10.  
    11. void FixedUpdate ()
    12.     {
    13.         //Jump
    14.         if (Input.GetButton("Jump") && isGrounded())
    15.         {
    16.             rb.velocity = new Vector3(0, jumpForce, 0);
    17.         }
    18.          
    19.         //Movement
    20.         float moveHorizontal = Input.GetAxis("Horizontal");
    21.         float moveVertical = Input.GetAxis("Vertical");
    22.  
    23.         Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
    24.         rb.velocity = movement * speed;
    25.     }
    Thanks in advance.;)
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    The problem is that you're overwriting the velocity with your 'movement' variable. Try changing the 'y' portion of movement so it's "rb.velocity.y".
     
    PajamaJohn likes this.
  3. Fab4

    Fab4

    Joined:
    Sep 30, 2012
    Posts:
    114
    Forces apply acceleration on your rb's
    Acceleration changes velocity over time
    To set the velocity to a specific value negates your effects of accelerate or add forces, but also all previous set velocity values. As methos already said you overwrite your velocity result in your script. So the first if statement can never be used in the running game.
     
    PajamaJohn likes this.
  4. PajamaJohn

    PajamaJohn

    Joined:
    Dec 2, 2017
    Posts:
    20
    Thanks! I notice when I did changed y in ‘movement’ variable to rb.velocity.y, it was also being calculated by speed; which did produce some interesting result. Of course, larger numbers send the player object skyward immediately, but smaller numbers gave it nice quick bounces when holding the space key. Once again, thanks you guys for clearing that up for me.