判断对象是否在视线内

// Cast a sphere with the desired distance. Check each collider hit to see if it is within the field of view. Set objectFound
    // to the object that is most directly in front of the agent
    /// <summary>
    /// Withins the sight.
    /// </summary>
    /// <returns>The sight.</returns>
    /// <param name="transform">玩家</param>
    /// <param name="fieldOfViewAngle">可视角度</param>
    /// <param name="viewDistance">可视距离</param>
    /// <param name="objectLayerMask">对象层</param>
     public static Transform WithinSight(Transform transform, float fieldOfViewAngle, float viewDistance, LayerMask objectLayerMask)
    {
        Transform objectFound = null;
        var hitColliders = Physics.OverlapSphere(transform.position, viewDistance, objectLayerMask);
        if (hitColliders != null) {
            float minAngle = Mathf.Infinity;
            float angle = 0;
            Debug.Log(hitColliders.Length);
            for (int i = 0; i < hitColliders.Length; ++i) {
                // The hit agent needs to be within the field of view of the current agent
                 angle = Vector3.Angle( hitColliders[i].transform.position - transform.position , transform.forward);

                if (angle < fieldOfViewAngle) {
                    RaycastHit hit;
                    // The hit agent needs to be within view of the current agent

                    Vector3  position = new Vector3(transform.position.x,1f,transform.position.z);
                    Vector3 targetPosition = new Vector3(hitColliders[i].transform.position.x,1f,hitColliders[i].transform.position.z);
                    Debug.DrawLine(position, targetPosition - position);

                    if(Physics.Raycast(position, targetPosition - position, out hit)){
                        if (hit.transform.Equals(hitColliders[i].transform)) {
                            // This agent is within sight. Set it to the agentInSight GameObject if the angle is less than any of the other agents
                            if (angle < minAngle) {
                                minAngle = angle;
                                objectFound = hitColliders[i].transform;
                            }
                        }
                    }
                }
            }
        }
        return objectFound;
    }

 

转载于:https://www.cnblogs.com/88999660/p/3732286.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值