人物视野检测是游戏开发中非常常见,下面是相关代码
public float fieldOfView;//视野度数
bool ViewCheck()
{
Vector3 forward = transform.forward;//人物前方正方向
Vector3 playerDir = other.transform.position - transform.position;//人物到被检测物体的方向
float temp = Vector3.Angle(forward, playerDir);//求出角度
RaycastHit hitInfo;
//向被检测物体发射射线,为了判断之间是否有障碍物遮挡
bool res = Physics.Raycast(transform.position + Vector3.up, other.transform.position - transform.position, out hitInfo);
if (temp < 0.5f * fieldOfView && (res == false || hitInfo.collider.tag == "item"))
{
return true;//被检测物体在视野中
}
return false;//被检测物体不在视野中
}