Problem with AddForce OnCollisionEnter

In my 2D game, I’m trying to knock back the player when he collides with a specific moving object using the code below. The problem is, once the player enters the collision with that object, the player keeps moving, as if the force is applied continuously. Any idea on how to fix this?

private void OnCollisionEnter2D(Collision2D collision) {
    var collider = collision.collider;
    if (collider.tag == "KnockBackObstacle" && !pushed)
    {
        Vector2 difference = (collider.transform.position - transform.position).normalized;
        Vector2 force = difference * knockbackForce;
        RB.AddForce(force, ForceMode2D.Impulse);
        pushed = true;
    } }

2 Answers

2

Your force vector needs to be reversed.
Create a vector that is directed away from the collider.

Try this:
Vector2 difference = (transform.position - collider.transform.position).normalized;

Thanks for the reply, but the problem persists. Once collided, player won't stop going in that direction.

You might want to check that the OnCollisionEnter2D method is being called at all. You should also try increasing the force to see if that was the problem. You should also change ForceMode2D.Impulse to ForceMode2D.VelocityChange if you don’t want the force to be affected by the mass of the player. Finally, check that the pushed flag is reset (set to false) and that “KnockBackObstacle” is spelled correctly on the gameObject’s tag with the exact same capitalization. The tag should also be set on the same gameObject that has the collider. Not any of the parent or child objects.

And like Sarith-Rovio said, you need to reverse the force vector as well. Otherwise, the force will launch the player into the collider.

The collision is detected. I tried the same code to make the player dash, but I encounter the same problem. Here, the player goes in the direction I want, but once I add the force, it is applied to the RigidBody2D constantly, even though I call the function only once: player.RB.AddForce(playerData.dashVelocity * _dashDirection, ForceMode2D.); Also, I can't change the ForceMode to VelocityChange, only Force or Impulse..

Anyway, I finally got it using Rigidbody2D.velocity and setting up a fixed time after which to reset player's velocity. Thanks for the help guys <3