[Rigidbody] Don't let objects move through each other, but don't apply forces

Hi guys,

First of all I’d like to apologize if I posted this in the wrong forum. If I did, could a mod please move it?

Anyways, let’s get down to business. I’m making a 2D platformer/fighter and I’d like to use a rigid body in order to use gravity and the likes. I ran into a problem however. Both fighters will get a rigidbody and a collider. I don’t want them to move through each other, but I don’t want them to apply forces to each other also. I tried several things buf I can’t seek to get this working. Any guidelines? Thanks in advance!

Well, if they’re not applying forces to each other, what ARE they doing when they would otherwise move through each other?

I’ll assume for the moment that your answer would be “stop moving”. Set their colliders to trigger, and on their “OnTriggerEnter2D” event, set their velocities to zero. You can make this as complicated as you like, for instance, if you simply zero out the vector in each other’s direction, they’ll slide past each other, and you could check and modify their positions to prevent partial overlap, and so on.

If you need them to collide normally with other objects, then leave the normal collider, and give them a child object with the trigger collider. Then, use layers to make the triggers collide with just each other and the normal colliders interact with other geometry.

You could do two Linecasts in front of your character in the direction they’re moving, from the top of your collider and the bottom. If the linecasts come back true for hitting an object in the Player or Enemy layer, then their horizontal velocity is set to 0, so they can only move away if they jump, turnaround, or the other player moves away.

Thanks guys! I went with Invertex’s approach and it works quite well! Jump will be a little bit harder, but I guess I can reuse some of the code and move the player around while jumping so they don’t get stuck within each other. It’s a shame they haven’t added the function 2dCollider.bounds yet though, but I can work around that I suppose.

There’s a workaround here:
http://forum.unity3d.com/threads/211486-Physics2D-Bounds-and-Extents