5.随机徘徊
我们希望场景中有随机移动的单位,如巡逻的士兵 吃草的牛羊,往往我们在场景中设置几个点让单位在几个点中随机移动,这样会出现一种情况,单位突然掉头,Craig Reynolds突出的随机徘徊解决了这个问题
代码语言:javascript复制public class SteeringForWander : Steering {
public float wanderRadius;//Wander半径
public float wanderDistance;//Wander距离
public float wanderJitter;//每秒加到随机位移的最大值
private Vector3 desiredVelocity;
private Vehicle m_vehicle;
private float maxSpeed;
private Vector3 circleTarget;
private Vector3 wanderTarget;
// Use this for initialization
void Start () {
m_vehicle = GetComponent<Vehicle>();
maxSpeed = m_vehicle.maxSpeed;
//选圆上一个点作为初始点
circleTarget = new Vector3(wanderRadius * 0.5f, 0, wanderRadius * 0.3f);
}
public override Vector3 Force()
{
//随机位移
Vector3 randomDisplacement = new Vector3((Random.value - 0.5f) * 2 * wanderJitter, 0, (Random.value - 0.5f) * 2 * wanderJitter);
//从初始点加上一个随机位移
circleTarget = randomDisplacement;
//将得到的新点进行投射到圆弧上
circleTarget = wanderRadius * circleTarget.normalized;
wanderTarget = m_vehicle.velocity.normalized * wanderDistance circleTarget transform.position;
desiredVelocity = (wanderTarget - transform.position).normalized * maxSpeed;
return desiredVelocity - m_vehicle.velocity;
}
}
Wander.gif
6.避开障碍
通过在AI前方发射一条一定长度的射线来检测AI前方是否有需要躲避的物体,在有障碍时,我们给AI一个向量为向前方的向量加上障碍中心到AHead的向量,来让AI物体避开障碍.
代码语言:javascript复制public class SteeringForCollisionAvoidance : Steering {
public Vehicle m_vehicle;
private float maxSpeed;
Vector3 desiredVelocity;
float maxForce;
//避免障碍的力
public float avoidanceForce;
public float MAX_SEE_AHEAD = 2.0f;
GameObject[] allColliders;
// Use this for initialization
void Start () {
m_vehicle = GetComponent<Vehicle>();
maxSpeed = m_vehicle.maxSpeed;
maxForce = m_vehicle.maxForce;
if(avoidanceForce > maxForce)
{
avoidanceForce = maxForce;
}
allColliders = GameObject.FindGameObjectsWithTag("obstacle");
}
public override Vector3 Force()
{
RaycastHit hit;
Vector3 force = new Vector3(0, 0, 0);
Vector3 velocity = m_vehicle.velocity;
Vector3 normalizedVelocity = velocity.normalized;
//从AI向前发射一条射线,如果在需要避开障碍的范围内,进行当前前方加一个原点到前方的向量和来作为新的力
if (Physics.Raycast(transform.position,normalizedVelocity,out hit, MAX_SEE_AHEAD * velocity.magnitude / maxSpeed))
{
Vector3 ahead = transform.position normalizedVelocity * MAX_SEE_AHEAD * (velocity.magnitude / maxSpeed);
force = ahead - hit.collider.transform.position;
force *= avoidanceForce;
}
return force;
}
}
CollisionAvoidance.gif