关于Unity3d中的LayerMask使用

最近看别人写的Demo,里面这个Linecast字段的LayerMask参数看了半天也没看懂

void Update()
    {
        // The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
        grounded = Physics2D.Linecast(transform.positiongroundCheck.position1 << LayerMask.NameToLayer("Ground"));  

        // If the jump button is pressed and the player is grounded then the player should jump.
        if(Input.GetButtonDown("Jump") && grounded)
            jump = true;
    }


后来去官网看,半天也没个例子,还是google吧,在网上看到各路大神的解释,终于明白了,LayerMask实际上是一个位码操作,在Unity3d中Layers一共有32层,这个是不能增加或者减少的:


摘自官网:

Layers are used throughout Unity as a way to create groups of objects that share particular characteristics (see this page for further details). Layers are primarily used to restrict operations such as raycasting or rendering so that they are only applied to the groups of objects that are relevant. In the manager, the first eight layers are defaults used by Unity and are not editable. However, layers from 8 to 31 can be given custom names just by typing in the appropriate text box. Note that unlike tags, the number of layers cannot be increased.


所以那个LayerMask实际上是用Int32的32个位来表示每个层级,当这个位为1时表示使用这个层,为0时表示不用这个层。


回到上面的例子:

1 << LayerMask.NameToLayer("Ground")

这一句实际上表示射线查询只在Ground所在这个层级查找。


再来看看NameToLayer是干嘛的。

官网解释:

Description

Given a layer name, returns the layer index as defined by either a Builtin or a User Layer in the Tag Manager.

是返回的该名字所定义的层的层索引,注意是从0开始。关于Unity3d中的LayerMask使用

你可能感兴趣的:(关于Unity3d中的LayerMask使用)