rigidbody.velocity.x/y/z - Problem

Hi!

I want to move a rigidbody without affecting the gravity-effect.
So I tried

rigidbody.velocity.x = targetVelocity.x;

but I keep getting:
“Cannot modify a value type return value of…[]”
Some people wrote that it’s working for them but how?

BTW:

rigidbody.velocity = targetVelocity; //targetVelocity is a Vector3 - (1f,0f,0f)

That works, but the object falls very slow. If I change the .Y in targetVelocity to something >1.0f and .useGravity = false, it gets stuck.

Maybe someone can guide me to the point I’m missing?

Try this:

Vector3 v3 = rigidbody.velocity;
v3.x = 1.0;
v3.z = 0.0;
rigidbody.velocity = v3;

Note if you want to turn gravity off and to simulate standard gravity, use -9.8 for the ‘y’ value.

Also you could do:

rigidbody.velocity = new vector3(targetVelocity.x, rigidbody.velocity.y, rigidbody.velocity.z);

Yeah completely useless comments for a beginner. Issues like these clearly shows what kind if a project managing does unity do for tutorials. Another wasted junk video tutorial on the topic of space shooter game is added to the junk space in internet for this stupid problem. Yet there is no clear definition of guidance to show people how to solve it. Shame on you.

All the other solutions didn’t work for me.

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