仅在两层上进行光线投射并进行位移以获得位掩码

Raycast only on two layers with bit shift to get the bit mask

我也读过 this post and in the part 2) Use Layers of Leosori's answer he use bit shift to get the bit mask. I wanted to have an explanation of how bit shift work (I didn't found my answer on the manual

示例中显示了如何仅在第 8 层进行投射:

int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.

那么,如何使用位移位同时得到第9层和第10层的位掩码呢?

在我的项目中,我在播放器上投射了一些光线,以便能够知道他是否看到了某些特定对象(第 10 层)。如果物体在墙后面(第 9 层),玩家应该看不到它。我想在两个图层上进行光线投射并测试 hit.collider.gameObject.tag 是否为 "seekObjects"。我知道还有其他解决方案可以做到这一点,但我想了解位移的工作原理。

主要使用 &|~<</>> 运算符来操作各个位。

示例(带字节):

// single value
byte a = 1; // 00000001

// shift "a" 3 bits left
byte b = a << 3; // 00001000

// combine a and b with bitwise or (|)
byte c = a | b; // 00001001

因此,在您的情况下,要设置第 9 位和第 10 位,请执行:

int layerMask = ( 1 << 9 ) | ( 1 << 10 );

请注意,我们使用的是 | 而不是 ||,这是逻辑或。