Hey guys thanks for stopping by,
I just tried to write a function, which allows my character to move through certain layers (in my example the layer with index 9).
I managed to change the Collision Matrix in the script:
Physics2D.SetLayerCollisionMask (gameObject.layer, (~(~Physics2D.GetLayerCollisionMask (gameObject.layer) | (1 << 9))));
I checked in the Project Settings > Physics2D, it works.
My Problem however is that if I stand on an object with layer 9 I don’t fall through it rightaway, but I have to jump once before the change ist noted.
Any ideas how to fix this?
The collision matrix isn’t designed to change all existing contacts in realtime. If we were to do this, we’d have to re-evaluate every single contact in the world which could be very expensive and is easily abused.
If you want to quickly cause all the contacts on a specific Rigidbody2D to be re-evaluated then you can toggle the Rigidbody2D.simulated property.
When you set this to false, all collision objects stay in memory but are not simulated. Also, any existing contacts for Collider2D attached to that Rigidbody2D are removed. When you set this to true, all the collision objects are simulated again and, during the next FixedUpdate, all contacts are calculated which will use the collision layer matrix at that time.
So in short, you can change the collision matrix and toggle the simulated property on any Rigidbody2D you wish to update.