以上一篇文章基类为基础,增加Steering的派生类
----SteeringForSeek类 靠近行为类。
----SteeringForFlee类 逃跑行为类。
靠近行为解读:
靠近行为类就是为问题提供实际操控力,从而使物体具备某种行为。
问题①:
基类的程序运行过程会出现,当物体不具备初速度,并且初始朝向与速度朝向不一致的时候,物体发生奇怪轨迹(并非从正面朝向移动到目标位置)。
void Start () {
velocity = transform.forward;//初速度为开始时候的朝向
controller = GetComponent<CharacterController>();
theRigidbody = GetComponent<Rigidbody>();
moveDistance = new Vector3(0, 0, 0);
base.Start();
}
解决:可以从AILocomotion类中的start 为velocity添加一个初始值为当前物体朝向。(此方法只作临时解决问题使用)
问题②:
解决:注意这里的 Skin Width 宽度过大,会把物体太高,使得两问题不在同一水平线上,而导致出现奇怪的运动轨迹。
逃跑行为解读:
靠近行为类代码实现:(通过计算作用力来控制物体移动的操控力)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SteeringForSeek : Steering {
//寻找的目标
public GameObject target;
//预期速度
private Vector3 desiredVelocity;
//获取被操控的AI角色,以便查询这个AI角色的最大速度信息;
private Vehicle m_vehicle;
//最大速度
private float maxSpeed;
//是否在二维平面上
private bool isPlanar;
// Use this for initialization
void Start () {
//获取组件以及读取数据
m_vehicle = GetComponent<Vehicle>();
maxSpeed = m_vehicle.maxSpeed;
isPlanar = m_vehicle.isPlanar;
}
public override Vector3 Force()
{
//通过两个位置求出物体到目标的向量
desiredVelocity = (target.transform.position - transform.position).normalized * maxSpeed;
if (isPlanar)
desiredVelocity.y = 0;
//通过向量相减,得出驱使物体达到目标的操控力
return (desiredVelocity - m_vehicle.velocity);
}
}
逃跑行为类代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SteeringForFlee : Steering {
public GameObject target; //远离目标
public Vector3 desiredVelocity; //期望速度
public Vehicle m_vehicle; //操控力作用的物体
public float maxSpeed; //作用最大速度
public float fearDistance = 20; //逃跑距离
private void Start()
{
m_vehicle = GetComponent<Vehicle>();
maxSpeed = m_vehicle.maxSpeed;
}
public override Vector3 Force()
{
Vector3 tmpPos = new Vector3(transform.position.x, 0, transform.position.z);
Vector3 tmpTargetPos = new Vector3(target.transform.position.x, 0, target.transform.position.z);
//如果AI与目标距离大于逃跑距离,那么返回0向量
if (Vector3.Distance(tmpPos, tmpTargetPos) > fearDistance)
return new Vector3(0, 0, 0);
//如果小于逃跑距离,那么计算逃跑的操控力
desiredVelocity = (transform.position - target.transform.position).normalized * maxSpeed;
return (desiredVelocity - m_vehicle.velocity);
}
}
参考书籍:《unity3d人工智能编程精粹》 王洪源等著