- Home /
How to add a 2D explosion force to players with physics based movement?
I am prototyping a top-down 2D local coop battle game and I am trying to add an explosion that will add force to players and give them a knockback effect. I have the process of creating the explosion and detecting all the players with the radius of the explosion working correctly.
The issue I am having it I don't know the proper combination of how to combine the physics based movement along with the explosion force to get my desired effect (which would be to have the player be knocked back).
Things I have tried:
Initially my movement was:
Vector2 newPosition = rigidBody.position + _movementInput * speed * Time.fixedDeltaTime; rigidBody.MovePosition(newPosition);
and apply the explosion force with
rigidBody.AddForce(direction * _explosionForce, ForceMode2D.Force);
but this made the player instantly translate instead of have a "pushed" effect.
I tried using the ForceMode2D.Impluse
with the MovePosition
but they don't seem to work together.
When I tried moving the player by their velocity
rigidBody.velocity = _movementInput * speed * Time.fixedDeltaTime;
and using
rigidBody.AddForce(direction * _explosionForce, ForceMode2D.Impulse);
the move velocity would override the velocity changed by the AddForce.
I tried added to the rigidBody's position as my movement method
rigidBody.position += _movementInput * speed * Time.fixedDeltaTime;
but when the explosion force is applied it doesn't stop, the player continues like they are on a frictionless surface.
What is the best way I can add an explosion force to a player with physics based movement?
The reason I am using physics based movement is that I have walls and other obstacles I don't want the players to be able to move through. From my understanding it won't work if you move the player with the transform and then have them interact with colliders and other physics elements.