Search code examples
unity-game-enginegame-physics

How to use AddForce and Velocity together?


I have the jump component who use the AddForce for jumping and the movement component who move left and right using the Velocity.

If you don't move the character when your are jumping the jumping will be fine but when you move the character and jump at the same time then the movement component will break the jumping because the velocity is setting up a Vector2 point where define the Y axis too. I tried to use the current Y axis from the transform component in the movement but even that doesn't work.

What I should do for fix the problem between AddForce and then use Velocity?


Solution

  • It seems your move function is creating a new velocity vector and overwriting the existing one.

    Vector2 velocityVector = rigidbody.velocity;    
    
    velocityVector.x += movement * force;
    
    rigidbody.velocity = velocityVector;
    

    This will retain the existing velocity, both X and Y, and modify it. You will of course need to add deceleration (usually I use something along the lines of if(grounded) velocityVector.x *= 0.999f;, but I'm sure more fancy maths exists for more realistic deceleration) and some kind of maximum speed (again, I keep things simple and use similar to if(velocityVector.x > maxSpeed) velocityVector.x = maxSpeed;).