- Home /
OverlapCircleAll, layerMask ( Problem)
Hi,
this is my code,
if(targetFood == null)
{
Collider2D[] allFood = Physics2D.OverlapCircleAll(antPosition, viewRadius, 7);
if(allFood.Length > 0)
{
Debug.Log("Find Food");
//Select one food Randomly
Transform food = allFood[Random.Range(0, allFood.Length)].transform;
//Find Dir to Food
Vector2 dirToFood = (food.position - transform.position).normalized;
//Search is it in ant's view angle (Simulating that ant smell that food)
if(Vector2.Angle(transform.position,dirToFood) < viewAngle / 2)
{
food.gameObject.layer = takenFoodLayer;
}
targetFood = food;
}
}
I have foods in my scene and ants randomly move until they find food. I only need to detect foods. I make "Food" layer for foods. and it's layer 7. but it's not debug when food in it range. but when I remove 7, it work. but it work for every layers.
have a good day, thanks.
Answer by Aluminum18 · Dec 29, 2021 at 02:53 AM
The LayerMask is acctually not a number, it is bitmask. You can use LayerMask.GetMask ("YourLayerString") to get the mask then past this mask into the Physics function.
You can find an example of using LayerMask here LayerMask
When you remove "7", the method works for all layers because it uses the default params which is EveryThing
Answer by Bhanuka_Dassanayake · Jan 01 at 07:57 PM
Actually I find a way, in this I need it for layer 7 and it's not work. but when I use 1 << 7 instead of 7, it work. can you please tell me if you know what this mean (1 << 7) it to work.
Collider2D[] allFood = Physics2D.OverlapCircleAll(antPosition, viewRadius, 1 << 7);
"<<" is left bit shifting operator (">>" also exists as right bit shifting). integer in C# is a 32-bit data type. Value 1 is presented as
0000_0000_0000_0000_0000_0000_0000_0001. 1 << 7 turns it into
0000_0000_0000_0000_0000_0000_1000_0000 which is the actual value of Layer "7".
The number you see in Layer settings represents how many bit you need to left shifting to get it actual value.
Your answer
Follow this Question
Related Questions
OverlapSphere doesn't detect colliders 1 Answer
Does adding a Layermask improve efficieny of Physics.OverlapSphere? 1 Answer
OverlapSphere ignoring all colliders when I use the layerMask parameter. 1 Answer
Physics2D.Raycast is fine, I'm an idiot 2 Answers
Replacing OverlapSphere with colliders (Detecting weapon collision with enemies - SOLVED) 1 Answer