I’m currently working on a 2D game, and I was wondering if there is anyway I can use the Layer Collision Matrix to disable collisions between layers, but not ignore triggers?
Right now, I need the Player layer and the Item layer to ignore collisions, that way the player doesn’t push items around when he touches them before he picks them up. However, I need the player to be able to pick up items, so it would be excellent if I could disable collisions, but not the triggers.
Here’s a solution I’ve come up with. It checks each collider in the scene, disables all layer collision ignores, and then enables collision ignores between colliders that are not triggers, so you can use the layer collision matrix to ignore collisions between game objects, but keep the triggers still enabled. It makes use of a custom tuple class, because tuples are not supported in .NET 3.5, which you can find here: https://gist.github.com/destinhebner/76f668b2b7705f9890ba8dec13503ab8
public static void UpdateCollisionLayerMatrix()
{
List<Tuple<Collider2D, Collider2D>> collidersToUpdate = new List<Tuple<Collider2D, Collider2D>>();
Collider2D[] colliders = FindObjectsOfType(typeof(Collider2D)) as Collider2D[];
if (colliders == null) return;
foreach (Collider2D colliderA in colliders)
{
foreach (Collider2D colliderB in colliders)
{
if (colliderA.gameObject == colliderB.gameObject) continue;
if (Physics2D.GetIgnoreLayerCollision(colliderA.gameObject.layer, colliderB.gameObject.layer))
{
collidersToUpdate.Add(new Tuple<Collider2D, Collider2D>(colliderA, colliderB));
}
}
}
foreach (Tuple<Collider2D, Collider2D> tuple in collidersToUpdate)
{
Physics2D.IgnoreLayerCollision(tuple.ItemA.gameObject.layer, tuple.ItemB.gameObject.layer, false);
if (!tuple.ItemA.isTrigger && !tuple.ItemB.isTrigger)
{
Physics2D.IgnoreCollision(tuple.ItemA, tuple.ItemB, true);
}
}
}
You can just set the items’ colliders “Is Trigger” value to true (and leave the collision matrix checked). This means that the OnTriggerEnter/OnTriggerEnter2D functions will be called, but the items will not react to Physics (being bumped into by other colliders)