RaycastHit2D的隐式转化

在学习Unity官方平台提供的ML-Agents强化学习示例时遇到了一个问题,以前没有注意过,记录一下。

ML-Agents强化学习示例:ML-Agents强化学习示例

在这个示例中,笔者在PlatformerAgent.cs中给出了一个IsGrounded的方法来判断主角是否站在地面上,代码如下:

public bool IsGrounded(Vector2 position)
    {
        Vector2 adjustedPosition = new Vector2(position.x, position.y + .5f);
        Vector2 direction = -Vector2.up;
        LayerMask layerMask = 1 << 31;
        RaycastHit2D grounded = Physics2D.Raycast(adjustedPosition, direction, 1f, layerMask);

        return grounded;
    }

在这个场景中,笔者将地面的layer设为了第31层,所以使用了layerMask = 1 << 31来指定Ground的layer。再往下看我就不太明白了,获得的grounded变量是RaycastHit2D类型,但是却能作为bool类型的返回值。到RaycastHit2D的声明中找到了这样一句话

 public static implicit operator bool(RaycastHit2D hit);

继续在网上查找资料后找到了git中一个unity反编译的工程:unity-decompiled

其中RaycastHit2D.cs中有这样一段

public static implicit operator bool(RaycastHit2D hit)  {  

    return (Object) hit.collider != (Object) null;  

扫描二维码关注公众号,回复: 2721299 查看本文章

}

所以RaycastHit2D重载了bool运算,做了隐式转换。

猜你喜欢

转载自blog.csdn.net/stone002/article/details/81537641