rigidbody controlling C# vs JS

Hello all,

Ok here is the problem in JS i can type:

rigidbody.velocity.y = 5;

and nothing is wrong. When i try that in C# unity doesn’t let me.
I shoul probably write my intention as well. i want to apply gravity. this is the code i use in JS and works perfect

function Update ()
{
thisRigidbody.velocity.y -= gravity * Time.deltaTime;
}

Is there no simple way to do that?

edit : btw i forgot to add i see a lot of answers that suggests to chance the code to rigidbody.velocity = new Vector3( rigidbody.velocity.x, gravity * Time.deltatime );

but that trick or way just won’t do cause character stops when i try simillar stuff

The second way is the correct way to do it in c#… however, you can also do this if you prefer

Vector3 rbVelocity;

void Update()
{
 rbVelocity = rigidbody.velocity;

 rbVelocity.y = gravity * Time.deltaTime;

 rigidbody.velocity = rbVelocity;

}

In your first one, you’re subtracting gravity. In the second one, you’re setting it to gravity. The correct alternative would be:

rigidbody.velocity = new Vector3( rigidbody.velocity.x, rigidbody.velocity.y - gravity * Time.deltatime );

You can try:

        Vector3 vel = rigidbody.velocity;
        vel.x = 5;
        rigidbody.velocity = vel;

or

rigidbody.velocity += new Vector3(0, -gravity * Time.deltatime, 0);

In you last example you miss the velocity .y and .z components.
(I am not sure if your gravity is a positive or negative value) :slight_smile:

SOLVED IT. here is the result

:smile:

i did the subtraction and added with the velocity.x evey frame so it applied it little by little and had to make a if statement to stop it. thank you guys

void  MoveRight()
    {
        rbd.velocity = new Vector2( speed * 1, 0f);
    }
void MoveLeft()
    {
        rbd.velocity = new Vector2( speed * -1, 0f);
    }
void  Jump()
    {
        rbd.velocity = new Vector2( rbd.velocity.x , jumpSpeed);
        playerState = PlayerState.moving;
    }
void FixedUpdate()
{
if ( !isGrounded )  //this becomes false when i stop touching floor at OnCollisionExit2D()
        {
            force.y -= gravity * Time.deltaTime;
            rbd.velocity = new Vector2( rbd.velocity.x, force.y );
        }
}

That character jumps with the happiness of a coder who has just figured out how to make his character jump. :wink: