- Home /
How to set velocity on a single axis only?
I know we can set velocity by using
rigidbody.velocity = new Vector3(hori * 5, ver * 5, 0);
But how do I set the velocity of a single axis? I tried
rigidbody.velocity.x = 5f;
But it's a return type and doesn't work.
Any help?
Answer by PaulCool · Jun 17, 2013 at 05:51 AM
Copy the value of velocity to a vector of your own, set the x component to 5, then copy it back. Something like this:
Vector3 v = rigidbody.velocity;
v.x = 5.0f;
rigidbody.velocity = v;
I know this is old, but this StackOverflow answer explains why new variable is needed - https://stackoverflow.com/a/1747702
rigidbody.velocity.x = 5.0f;
This code tries to modify copy of struct Vector3. After that the copy discarded, because it's not stored in any variable nor passed somewhere
Vector3 v = rigidbody.velocity; v.x = 5.0f; rigidbody.velocity = v;
This code copies struct, changes it's property x (this can be done, as Vector3 is mutable and v is concrete variable that won't be discarded), and then copies the whole resulting struct back to velocity property
Answer by Gaming_geko · Oct 17, 2017 at 07:00 PM
Other options mess up the gravity, at least in 2d.
amazing solution:
yVel = rb2d.velocity.y; rb2d.velocity = new Vector2(Input.GetAxis("Horizontal"), yVel);
The problem is, it is getting the velocity (for me Y) and setting it, every frame, however the script is getting the velocity (for me y so i'm going to be saying it's y) let's say 1, so it sets it to 1, great right? wrong, gravity is constant, however the object is going from static to moving, so gravity accelerates the object, however the code rigidbody.velocity = new Vector2 (10f, rigidbody.velocity.y);
will keep the y velocity constant, not allowing for the previously mentioned acceleration. to fix this, I made a variable, specifically for the Y velocity, but it gets set before the velocity does (it's in the Update method), so the acceleration can happen.
I had a major problem with this and it was a Eureka moment xD