CapsuleCollider2D.Cast() can't find any colliders when used with ContactFilter2D with LayerMask
I'm making an endless-runner-esque game. When my player runs into an obstacle, he loses one life and gets set a safe distance back. I now want to make sure that he isn't put right on top of another obstacle when he is reset.
For this, I wanted to use the CapsuleCollider2D.Cast() which has an overload where you can pass in a ContactFilter with a Layermask which I wanted to use to make sure I only test against one Layer. When I use the CapsuleCollider2D.Cast() without passing in the contactfilter, it works as intended. When I use the contactfilter, it doesn't detect the obstacles. This is how I set up the filter:
private ContactFilter2D obstFilter;
obstFilter.useTriggers = false;
//Layer 10 is my layer for obstacles as displayed in the inspector window
obstFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(10));
obstFilter.useLayerMask = true;
This is how the cast looks:
int collTest = myCollider.Cast(Vector2.down, obstFilter, hitBuffer, moveBackDist, true);
By just leaving out the "obstFilter", I get it to work. Do I missunderstand how ContactFilters work?
Thanks in advance for any help!
Ps: Not a native speaker, so bear with me please.
And yes, I made sure the obstacles are actually on the correct layer in my testing scenario.
I'm having the same (or very similar) issue. Did you ever find a solution to this, by any chance?
Answer by NoDumbQuestion · Jul 17, 2018 at 09:44 AM
You are mistook layer number and layer mask. You suppose to use:
obstFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(1 << 10));
1 << 10 mean only collide with layer 10
https://answers.unity.com/questions/8715/how-do-i-use-layermasks.html
Thanks! Seems odd considering that the function is named GetLayerCollision*$$anonymous$$ask*(), but it works. Appreciate the quick response