Unity Physics.Raycast 深入理解

Physics.Raycast 理解

方法原型与参数说明

 

其实这个函数有个很藏的很深的地方就是这个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;       

(Physics.Raycast(transform.position, Vector3.forward, Mathf.Infinity, layerMask))    Debug.Log("The ray hit the player");
第二种情况:除了第几层其他接受碰撞射线的检查则可以使用下面的方法

 int layerMask = 1 << 8;           

 layerMask = ~layerMask;

 第三种情况:如果不传入layermask这个值的话,那么默认的会值忽略 IgnoreRaycast 这个层级(unity默认的)

 

 

 

 

  • 15
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值