What does double less-than sign do?

I was looking through the code of Unity sample game and found this piece of code:

grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

So i wondered what does “<<” this sign do and how does this line return bool value?

1 Answer

1

<< is the left shift operator. It moves the bits in the first operand left by the number of places in the second operand.

Example. 1 << 2 returns 4. Let’s look at the bits to see why. Integer 1 in binary is 000000001. We tell the bits to move left two places producing binary 000000100. That represents the integer 4.


In Unity layers are stored as integers. User layer 6 is actually the number 6. LayerMask.NameToLayer returns the integer of the layer for the given name. If your “Ground” layer is layer 8, 1 << LayerMask.NameToLayer("Ground")) will return binary 100000000 which is the integer 256.


The Physics2D.Linecast third parameter is a bit mask. Each bit in the integer corresponds to a layer. The rightmost bit corresponds to layer 0. The next bit from the right corresponds to layer 1. The next bit from the right corresponds to layer 2. The next bit from the right corresponds to layer 3, and so forth up to layer 32.

Layer  9 8 7 6 5 4 3 2 1 0
Bits   0 0 0 0 0 0 0 0 0 0

Each bit can be either a one or a zero. A 1 means to match that layer, a zero means to not match. Using a layer mask of 1 (Binary 000000001 (1 << 0)) tells Physics2D.Linecast to only hit colliders on layer 0. Using a layer mask of 256 (Binary 100000000 (1 << 8)) tells Physics2D.Linecast to only hit colliders on layer 8. If Physics2D.Linecast hits a collider on the specified layers it returns true otherwise it returns false.

Thank you for the explanation, now it's a bit more clear for me)

–