方法原型与参数说明
其实这个函数有个很藏的很深的地方就是这个layermask, 一般情况我们获取layer的值都会是layermask.nametolayer 这个函数去取得对应的层级,然后把这个int形的参数给到函数使用。但是如果是使用了Physics.Raycast去获取碰撞物的时候,你怎么都获取不到被碰撞的物体。(即使你划线来表示你的射线,也会觉得好像没有任何问题)
最后在unity的官方上找到了说明
Casting Rays Selectively
Using layers you can cast rays and ignore colliders in specific layers. For example you might want to cast a ray only against the player layer and ignore all other colliders.
The Physics.Raycast function takes a bitmask, where each bit determines if a layer will be ignored or not. If all bits in the layerMask are on, we will collide against all colliders. If the layerMask = 0, we will never find any collisions with the ray.
上面说明了一个问题就是,这个值如果是使用物理来进行碰撞的时候是使用的位移操作来进行的,也就是这里的layermask获得的值还要进行位移
第一种情况:表示在第8层上检查碰撞信息
int layerMask = 1 << 8;
private RaycastHit hitInfo; //声明射线输出的RaycastHit
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //从相机发射到鼠标位置的射线
if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, layerMask)) {
Debug.Log("The ray hit the mouse");
}
第二种情况:除了第几层其他接受碰撞射线的检查则可以使用下面的方法
int layerMask = 1 << 8;
layerMask = ~layerMask;
第三种情况:如果不传入layermask这个值的话,那么默认的会值忽略 IgnoreRaycast 这个层级(unity默认的)
————————————————
版权声明:本文为CSDN博主「Dongo2」的原创文章