A line of code, I do not understand. 1<
grounded=Physics2D.Linecast(transform.position, groundCheck.position, 1<<LayerMask.NameToLayer("Ground"));
I know linescast, but the last codes 1<<LayerMask.NameToLayer("Ground")
What is the meaning, how to use it?
It is from this tutorial 2d platform game
Thanks!
It merely states that the linecast only checks on the layer called Ground.
Answer by YoungDeveloper · Sep 07, 2015 at 11:24 AM
It's layer specifying using bit shifting. It's very well explained here.
Answer by Suddoha · Sep 07, 2015 at 11:32 AM
It's a shifting operation. LayerMasks use the bits of an integer (4 bytes = 32 bits, thus you can have 32 layers) to store multiple layers in one integer efficiently. That means, you can combine any layers that you like and only need 4 bytes, i.e. a simple integer. LayerMasks.NameToLayer returns the index of a given layerName, for example you've got a layer called "myLayer" at the 9th position, which is, according to 0-based counting, the index 8.
That in turn means, if you want to use this layer in a LayerMask, you have to set the 9th bit of an integer.
Imagine you've got an integer, which is currently 0, that represents your list of layers (0 not set, 1 set)
0000 0000 0000 0000 0000 0000 0000 0000
You now have "myLayer" in the 9th slot in the layer list. According to that, you want the following LayerMask
0000 0000 0000 0000 0000 0001 0000 0000
As stated above, the method LayerMask.NameToLayer(...) returns the index (remember, it's 8) so you can now do the following. Start with 1 written in binary:
0000 0000 0000 0000 0000 0000 0000 0001
and shift it
once: 0000 0000 0000 0000 0000 0000 0000 0010
twice: 0000 0000 0000 0000 0000 0000 0000 0100
[...]
8 times: 0000 0000 0000 0000 0000 0001 0000 0000
Voila, you have the appropriate LayerMask for your layer.
what does*Layer$$anonymous$$ask.NameToLayer("Ground")* return?
an int?
Yes, Layer$$anonymous$$ask.NameToLayer "returns the layer index"
http://docs.unity3d.com/ScriptReference/Layer$$anonymous$$ask.NameToLayer.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612032724im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Gameobject Gravity 2D Script 0 Answers
How to get the layer id from a layer mask? 0 Answers
[Question] Unity C# Set a Player Class and refence issue 0 Answers