</pre><pre code_snippet_id="1607703" snippet_file_name="blog_20160312_2_2743111" name="code" class="csharp">//父类
//方便添加新感官
using UnityEngine;
using System.Collections;
/// <summary>
/// AI感官类
/// </summary>
public class Sense : MonoBehaviour {
public bool isDebug = true;
public Aspect.aspect aspectName = Aspect.aspect.Enemy;
public float detectionRote = 1.0f;
protected float elapsedTime = 0.0f;
//初始化感官
protected virtual void Initialise() { }
//更新感官
protected virtual void UpdateSense() { }
void Start()
{
elapsedTime = 0.0f;
Initialise();
}
void Update()
{
UpdateSense();
}
}
</pre><pre code_snippet_id="1607703" snippet_file_name="blog_20160312_11_8725111" name="code" class="csharp">
</pre><pre code_snippet_id="1607703" snippet_file_name="blog_20160312_8_1896341" name="code" class="csharp">//视觉感官实例化类
using UnityEngine;
using System.Collections;
public class Perspective : Sense {
public int FieldOfView = 45;//检测范围
public int ViewDistance = 100;//检测距离
private Transform playerTrans;
private Vector3 rayDirection;
/// <summary>
/// 发现player坐标
/// </summary>
protected override void Initialise()
{
playerTrans = GameObject.FindGameObjectWithTag("Player").transform;
}
protected override void UpdateSense()
{
elapsedTime += Time.deltaTime;
//检测需要感觉的范围内是否存在物体
if (elapsedTime >= detectionRote)
DetectAspect();
}
/// <summary>
/// 感觉范围内是否有物体
/// </summary>
private void DetectAspect()
{
RaycastHit hit;
//当前位置与player的位置的距离
rayDirection = playerTrans.position - this.transform.position;
//计算当前位置与players的位置是否在检测范围内
if ((Vector3.Angle(rayDirection, this.transform.position)) < FieldOfView)
{
//如果player在检测范围内
if (Physics.Raycast(this.transform.position, rayDirection, out hit, ViewDistance))
{
Aspect aspect = hit.collider.GetComponent<Aspect>();
if (aspect != null)
{
//更新朝向
if (aspect.aspectName == aspectName)
{
//输出检测到敌人
print("Enemy Detected");
}
}
}
}
}
void OnDrawGizoms()
{
if (!isDebug || playerTrans == null)
return;
Debug.DrawLine(transform.position, playerTrans.position, Color.red);
Vector3 frontRayPoint = transform.position + (transform.position * ViewDistance);
//在编译状态可视化
Vector3 leftRayPoint = frontRayPoint;
leftRayPoint.x += FieldOfView * 0.5f;
Vector3 rightRayPoint = frontRayPoint;
rightRayPoint.x -= FieldOfView * 0.5f;
Debug.DrawLine(transform.position, frontRayPoint, Color.green);
Debug.DrawLine(transform.position, leftRayPoint, Color.green);
Debug.DrawLine(transform.position, rightRayPoint, Color.green);
}
}
//作为实例化的触摸类
using UnityEngine;
using System.Collections;
public class Touch : Sense {
void OnTriggerEnter(Collider other)
{
Aspect aspect = other.GetComponent<Aspect>();
if (aspect != null)
{
if (aspect.aspectName == aspectName)
{
print("Enemy Touch Detected");
}
}
}
}
</pre><pre code_snippet_id="1607703" snippet_file_name="blog_20160312_11_8725111" name="code" class="csharp">