继续学习这本书,虽然跳过了一些章节,请原谅我选择性学习的方式,毕竟时间比较宝贵。
进入主题,今天要学习的是AI感知行为的基类,有三个,直接上代码了:
TriggerSystemManager 类:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TriggerSystemManager : MonoBehaviour
{
//感知列表
private List<Sensor> currentSensor = new List<Sensor>();
//触发列表
private List<Trigger> currentTrigger = new List<Trigger>();
//需要被移除的感知列表,例如死亡等情况需要移除
private List<Sensor> sensorToRemove;
//需要被移除的触发列表,例如死亡等情况需要移除
private List<Trigger> triggersToRemove;
void Start()
{
sensorToRemove = new List<Sensor>();
triggersToRemove = new List<Trigger>();
}
private void UpdateTriggers()
{
foreach (Trigger t in currentTrigger)
{
//如果需要被移除
if (t.toBeRemoved)
{
//加进移除列表中,这是因为不能直接在foreach中移除
triggersToRemove.Add(t);
}
else
{
//更新触发器内部信息
t.Updateme();
}
}
//清空触发列表
foreach (Trigger t in triggersToRemove)
{
currentTrigger.Remove(t);
}
}
private void TryTriggers()
{
foreach (Sensor s in currentSensor)
{
if (s.gameObject != null)
{
foreach (Trigger t in currentTrigger)
{
t.Try(s);
}
}
else
{
sensorToRemove.Add(s);
}
}
foreach (Sensor s in sensorToRemove )
{
currentSensor.Remove(s);
}
}
void Update()
{
UpdateTriggers();
TryTriggers();
}
/// <summary>
/// 用于注册触发器
/// </summary>
/// <param name="t"></param>
public void RegisterTrigger(Trigger t)
{
print("registering trigger " + t.name);
currentTrigger.Add(t);
}
/// <summary>
/// 用于注册感知器
/// </summary>
/// <param name="s"></param>
public void RegisterSensor(Sensor s)
{
print("registering sensor :" + s.name + s.sensorType);
currentSensor.Add(s);
}
}
Trigger 类 :
using UnityEngine;
using System.Collections;
public class Trigger : MonoBehaviour {
protected TriggerSystemManager manager;
//触发器的位置
protected Vector3 position;
//触发器的半径
public int radius;
//当前触发器是否要被移除
public bool toBeRemoved;
/// <summary>
/// 感知能否能被触发,触发的行为在派生类实现
/// </summary>
/// <param name="s"></param>
public virtual void Try(Sensor s)
{
}
/// <summary>
/// 更新内部状态
/// </summary>
public virtual void Updateme()
{
}
/// <summary>
/// 这个方法检查感知器s是否在触发器的作用范围内,
/// 如果是,返回true,否则false,它被try()调用,
/// 在派生类实现
/// </summary>
/// <param name="sensor"></param>
/// <returns></returns>
protected virtual bool isTouchingTrigger(Sensor sensor)
{
return false;
}
void Awake()
{
manager = FindObjectOfType<TriggerSystemManager>();
}
protected void Start()
{
toBeRemoved = false;
}
void Update()
{
}
}
sensor 类
using UnityEngine;
using System.Collections;
public class Sensor : MonoBehaviour {
protected TriggerSystemManager manager;
public enum SensorType
{
sight,
sound,
health
}
public SensorType sensorType;
void Awake()
{
manager = FindObjectOfType<TriggerSystemManager>();
}
void Start()
{
}
void Update()
{
}
public virtual void Notify(Trigger t)
{
}
}
原谅我作为原创发表,这本书的确很好,比我之前看到的一个外国大神写的《unity3d人工智能编程》更加详细和全面,我会每天发表一篇博客,作为学习记录的.......
人笨,跟着各路大神学习有汤喝就足够了