Search Unity

How to set velocity of only one axis?

Discussion in 'Scripting' started by KevNicholson, Feb 27, 2021.

  1. KevNicholson

    KevNicholson

    Joined:
    Feb 17, 2021
    Posts:
    18
    Right now for movement in the fixed update void I have:
    rb.velocity = new Vector 3 (xMovement, 0, 0);
    rb is a reference to my rigidbody 2d, and xMovement is a variable that switches between -10, 0, and 10 when you are using the a, and d keys. That code constitutes the left and right movement, and it works great. The problem is I would like to use addforce on the y axis to make it jump, but I can't because velocity.y is set to 0 every physics update. I need a way to change the above code so that it only affects the x axis. Please help. Thanks.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Get the velocity, set the .x of it, then set it back:
    Code (csharp):
    1. Vector3 vel  = rb.velocity;
    2. vel.x = xMovement;
    3. rb.velocity = vel;
     
  3. KevNicholson

    KevNicholson

    Joined:
    Feb 17, 2021
    Posts:
    18
    Thank you sir that works a treat. Can you please explain how so I can solve similar problems in the future. I don't know alot about coding
    Thanks
     
  4. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    369
    Velocity uses a Vector3, a structure of three floats (x,y,z).
    You create a new vector3 and pass that to your rigidbody.
    Code (CSharp):
    1. float x = 0;
    2. float y = 0;
    3. float z = 0;
    4. Vector3 velocity = new Vector3(x, y, z);
    5. rigidbody.velocity = velocity;
    6.  
     
  5. mpknecht

    mpknecht

    Joined:
    Aug 12, 2012
    Posts:
    2
    I do not understand how to get this to work with my code without using the xMovement variable. My code just looks like body.velocity = new Vector 3 (-5, 0, 0); Could someone please explain how the code should look after the adjustments are made. Thanks
     
  6. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258
    Structs are Value-Types. This means they are passed by value, not by reference.
    Thus, when you read the velocity from your rigidbody, you get it's value, not a reference to the actual velocity.
    You thus need to change this value, then write it back to the rigidbody. Changing the value itself will not change the rigidbody's velocity.

    if you only want to set the x-value, you can do:
    body.velocity = new Vector3(-5, body.velocity.y, body.velocity.z);

    You could also update it by doing:
    body.velocity += new Vector3(-5, 0, 0);

    Which would be the same as:
    body.velocity = body.velocity + new Vector3(-5, 0, 0);
     
    raymondy1 likes this.