1
votes

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.

2
why not use velocity to move your player too - BugFinder
@BugFinder It had the same result. The velocity of the knockback gets overwritten by the player movement velocity instantly. - Daniel Martinek
only if you manually set velocity, not add force - BugFinder
Right now, I have this for player (in player script): rb.MovePosition((Vector2)transform.position + velocity * Time.fixedDeltaTime); and this when enemy hits player (in enemy script): player.GetComponent<Rigidbody2D>().AddForce(velocity.normalized * knockback); - Daniel Martinek
Player will not move, if you're setting it's position with MovePlayer as it overrides any sort of impact from physics engine thus your velocity too - Eric

2 Answers

1
votes

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.

0
votes

Just in case someone else stumbles across this: Technically you can do what the TE initially wanted by replacing MovePosition(pos) with transform.position = pos.

This will maintain inertia\velocity etc. and might be what you need in very specific situations (in my case creating a custom type of non-stretchy hinge joint where the enforced position change is very small).

The main downside of this solution is that the physics engine can do unexpected things when the position is shifted into a solid collision. The engine will still try to resolve the situation and push the object out of a collision, but it doesn't know what direction it came from (unlike with MovePosition), shifting possibly in the wrong direction and thus let Objects clip through terrain. That's why in general it's not recommended to touch 'transform' when a rigidbody is applied.