AI视野扇形检测
在游戏中会找寻敌人,并产生攻击,那么首先是要判断是否在攻击范围内,且是可见的
下面就是利用扇形检测,来简单模拟眼睛这一个作用,比较简单,注释较少
简单列举了两种方式:
写的不好,欢迎指正:
代码如下:
1.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 扇形视线范围,用于绘制扇形,视觉
/// </summary>
public class Eye : MonoBehaviour {
public float MaxDistance = 5f;
public float MaxRadius = 90f;
public Transform target;
// Update is called once per frame
void Update () {
if (Vector3.Distance(target.position , transform.position) > 5f) //先判断距离
{
print("不在范围内");
}
else
{
//如果距离近的话,片段角度,是不是在视线范围内
//获取自身到目标的向量
Vector3 v = target.position - transform.position;
//在判断自身到目标的向量方向,跟自己正上方做个对比,就可以得到具体距离角度多少
float r = Vector3.Angle(v,transform.forward);
Debug.DrawRay(transform.position ,transform.forward * MaxDistance,Color.red);
Quaternion left = transform.rotation * Quaternion.AngleAxis(MaxRadius / 2, Vector3.down);
Quaternion right = transform.rotation * Quaternion.AngleAxis(MaxRadius / 2, Vector3.up);
Vector3 a = left * v;
Vector3 l = right * v;
Debug.DrawRay(transform.position ,transform.forward * MaxDistance + new Vector3(), Color.red);
Debug.DrawRay(transform.position, l, Color.red);
Debug.DrawRay(transform.position, a, Color.red);
//根据角度判断,
if (r <= MaxRadius / 2) //如果小于45度
{
print("在视线范围内");
}
}
}
}
2.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 扇形检测
/// </summary>
public class EyeS : MonoBehaviour {
public Transform target;
public float distance = 5f;
public float Radius;
// Update is called once per frame
void Update () {
float dis = Vector3.Distance(transform.position,target.position);
Vector3 norvec = transform.rotation * Vector3.forward * 5;
Vector3 temp = target.position - transform.position;
Debug.DrawRay(transform.position , norvec, Color.red);
Debug.DrawRay(transform.position, target.position, Color.red);
float radius = Mathf.Acos(Vector3.Dot(norvec.normalized ,temp.normalized)) *Mathf.Rad2Deg;
print(radius);
if (dis <= distance)
{
if (radius <= Radius *0.5f)
{
Debug.Log("在扇形范围内");
}
}
}
}
目前先列举两个,会继续更新的,欢迎关注: