Search code examples
unity-game-enginetopdown

Unity - AddForce() while using MovePosition() for movement


I was working on my top down game, but I got stuck. I am trying to make player be knockbacked when an enemy hits him(their rigidbodies collide).

Now the problem is I am using MovePosition for player movement and when I then use anything that will change the velocity of the players RB(setting velocity/AddForce()), the force/velocity is applied just for a split second. I think it is because I use the MovePosition which somehow ignores or resets the velocity.

Is there some way I can go around this without having to make the player controls based on adding forces with max velocity or with calculating how long will the knockback last for?

Shortly, I want the knock back smooth, because now I have to add a really high force to have really fast (basically instant) movement.


Solution

  • Try to rewrite it so that the physics engine take care of everything for you. You can try moving your object with the use of AddForce and while at "knockback" state you can utilise AddForce with Force.Impulse as a parameter. It should work as intended and will take the problem of the movement from your shoulders.