参考了一篇博客,简要写了下demo,代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Look();
}
[Range(0, 360)]
public float angle = 90f; //检测前方角度范围
[Range(0, 100)]
public float distance = 25f; //检测距离
public float rotatePerSecond = 90f; //每秒旋转角度
[Range(1, 50)]
public float accuracy = 1f; //检测精度
private bool Look()
{
float subAngle = angle / accuracy; //每条射线需要检测的角度范围
for (int i = 0; i < accuracy; i++)
if (LookAround(Quaternion.Euler(0, -angle / 2 + i * subAngle + Mathf.Repeat(rotatePerSecond * Time.time, subAngle), 0), distance, Color.blue))
return true;
return false;
}
//射出射线检测是否有Player
public bool LookAround(Quaternion eulerAnger,float _lookRange, Color DebugColor)
{
Debug.DrawRay(transform.position, eulerAnger * transform.forward.normalized * _lookRange, DebugColor);
RaycastHit hit;
if (Physics.Raycast(transform.position, eulerAnger * transform.forward, out hit, _lookRange)/* && hit.collider.CompareTag("Player")*/)
{
Debug.Log(hit.transform);
return true;
}
return false;
}
}
实现效果如图:
单次检测如下:
//放射线检测
private bool Look()
{
var _len = 30;
一条向前的射线
if (LookAround(Quaternion.identity, _len, Color.green))
return true;
var _lookAngle = 90;
var _lookAccurate = 5;
//多一个精确度就多两条对称的射线,每条射线夹角是总角度除与精度
float subAngle = (_lookAngle * 0.5f) / _lookAccurate;
for (int i = 0; i <_lookAccurate; i++)
{
if (LookAround(Quaternion.Euler(0, -1 * subAngle * (i + 1), 0), _len, Color.green)
|| LookAround(Quaternion.Euler(0, subAngle * (i + 1), 0), _len, Color.green))
return true;
}
return false;
}