unity的射线检测 和layer

fixedUpdate()

FixedUpdate()不受帧率影响,固定时间被调用

使用Physics api进行检测

layerMask 定义要在查询中包括哪些碰撞体层,可进行位运算。

LayerMask 是位掩码。使用 LayerMask.GetMask 和 LayerMask.LayerToName 可生成位掩码。
LayerMask mask = 1 << 2; 表示开启Layer2。
LayerMask mask = 0 << 5;表示关闭Layer5。
LayerMask.GetMask("Player")
LayerMask.LayerToName(1) 返回1层的名称
LayerMask.NameToLayer("TransparentFX")) 返回层的索引。

Physics.Raycast&&Physics.RaycastAll

/*public static bool Raycast (Vector3 origin, Vector3 direction, float maxDistance= Mathf.Infinity, 
int layerMask= DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction= QueryTriggerInteraction.UseGlobal);   返回是否有物体被射线检测到*/
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
    {
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);    //显示检测区域
        Debug.Log("Did Hit");
    }
/*public static RaycastHit[] RaycastAll (Vector3 origin, Vector3 direction, float maxDistance= Mathf.Infinity,
 int layerMask= DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction= QueryTriggerInteraction.UseGlobal);
向场景中投射射线并返回所有命中对象。注意,这些结果的顺序未定义。*/
 RaycastHit[] = Physics.RaycastAll(transform.position, transform.forward, 100.0F);

Physics.OverlapSphere && Physics.OverlapSphereNonAlloc

//public static Collider[] OverlapSphere (Vector3 position, float radius, int layerMask= AllLayers, QueryTriggerInteraction queryTriggerInteraction= QueryTriggerInteraction.UseGlobal);计算并存储接触球体或位于球体内部的碰撞体。
//public static int OverlapSphereNonAlloc (Vector3 position, float radius, Collider[] results, int layerMask= AllLayers, QueryTriggerInteraction queryTriggerInteraction= QueryTriggerInteraction.UseGlobal);
Collider[] colliders = Physics.OverlapSphere(mainplayer.transform.position,data.hp, 1 << 8);
int numColliders = Physics.OverlapSphereNonAlloc(center, radius, hitColliders);
posted @ 2021-02-04 16:24  melt00  阅读(345)  评论(0编辑  收藏  举报