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.
Get the velocity, set the .x of it, then set it back:
Vector3 vel = rb.velocity;
vel.x = xMovement;
rb.velocity = vel;
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
Velocity uses a Vector3, a structure of three floats (x,y,z).
You create a new vector3 and pass that to your rigidbody.
float x = 0;
float y = 0;
float z = 0;
Vector3 velocity = new Vector3(x, y, z);
rigidbody.velocity = velocity;
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
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);