Make Sure We Hit the Floor- Game Dev Series 100
Objective: use Physics2D.Raycast on specific layer.
When we using Raycast as colliding detection, it returns the first result no matter what it is. That would cause some problems.
For example, when I create a ground touching detection by using Raycasthit, it keep return the collider of Player as result. I need to make the Raycast ignore Player, more so, I need to make Raycast only return the result on specific layer.
Set the layer of ground
First, lets create a layer to all the ground. Select the floor objects and select Add Layer. The first blank column you can add should be on №8.
Once you type in “Ground”, you successfully set the floors to layer Ground.
Now we need to make our Player can only return this layer.
Set layer mask
Inside the script doing Raycast, you will see it says that using “int” as layerMask.
However, we could not use “8” as the integer in code. It use binary as the layer order in Unity. To explain this more clearly, here is a simple drawing about this concept.
In binary, layer 8 actually means moving the “1” 8 times to the left from very right. The result in binary would be from "000000001" to “100000000”. To present this result in code, we can use “1 << 8" as value of layerMask.
Once using layerMask to Raycast, it should no longer return the value of Player but the ground layer.
As we already know the meaning of “1 << 8" in code, we can actually use the integer of binary “100000000" to decimal, which is 256.
You should get the same result.
Now Raycast on wrong object will no longer be a problem.