Prevent rigidbodies pushing each other

I’m having an issue in the game I’m making:

My player character is being pushed around by enemies endlessly across the map and sometimes through Colliders.

I’ve tried changing the mass/forces of the 2 characters and I’ve also tried dynamic/kinematic settings but I’m confused as to how to prevent this from happening

I’m using a rigidbody 2d and a 2d box collider on both the player and the enemy.

Any ideas?

Layers control what can push what.

1 Like

Thanks for your help!

Well what I’m going for is for both the enemy+player to be unpushable by each other, but also not able to pass through each other, is this possible to set up via layers?

Another issue I’m having is that upon colliding it’s causing the camera to shake and distort the game world, is there a work-around for that?

You want to just prevent movement in the direction of the collision then. This is a bit of code you would script that would either intercept contacts (advanced) or just simply cancel out movement in the direction of the thing it can’t pass through.

There’s no built-in method to achieve this as it’s not a common thing for a physics engine. Usually 2D games that might do this have their own movement and collision code and don’t rely on Box2D.

1 Like

Alright thanks, I’ll look into cancelling out the movement based on direction, if it’s too complicated I wouldn’t mind the character+enemy pushing each other just as long as it was by a small amount rather than constantly sliding.

When things collide with anything, a quick and dirty way of solving it would be to do something like (untested) where rb is a reference to Rigidbody2D:

rb.velocity = Vector3.ProjectOnPlane(rb.velocity, collisionNormal);

This simply wipes out any movement toward normal but preserves everything else. It’s what you might consider sliding collision.

Thanks again for the help.

Would that be written like this and attached to the enemy controller?

private void OnCollisionEnter(Collision collision)
    {
        myRigidbody.velocity = Vector3.ProjectOnPlane(myRigidbody.velocity, collision.contacts[0].normal);
    }

Did it work?