摘自《unity3d人工智能编程精粹》
1,交通工具类,在AI架构模型中,通常把AI抽象为一个点,一般包含position,mass,velocity等等的信息。
而速度随着施加的力而变化,因此还要有maxSpeed和maxForce来进行限制。
using UnityEngine;
using System.Collections;
public class Vehicle : MonoBehaviour {
//这个AI角色包含的操纵行为列表
private Steering[] steerings;
public float maxSpeed = 10;
public float maxForce = 100;
protected float sqrMaxSpeed;
//角色质量
public float mass = 1;
public Vector3 velocity;
//转向速度
public float damping = 0.9f;
//间隔时间
public float computeInterval = 0.2f;
public bool isPlanar = true;
protected Vector3 steeringForce;
protected Vector3 acceleration;
protected float timer;
protected void Start()
{
steeringForce = Vector3.zero;
sqrMaxSpeed = maxSpeed * maxSpeed;
timer = 0;
steerings = GetComponents<Steering>();
}
void Update()
{
timer += Time.deltaTime;
steeringForce = Vector3.zero;
if(timer >computeInterval )
{
foreach (Steering s in steerings )
{
if(s.enabled )
{
steeringForce += s.Force() * s.weight;
}
}
steeringForce = Vector3.ClampMagnitude(steeringForce, maxForce);
acceleration = steeringForce / mass;
timer = 0;
}
}
}
2,真正操纵AI角色移动的类,包括计算每次移动的距离,动画等等。它派生自Vehicle
using UnityEngine;
using System.Collections;
public class AILocomotion : Vehicle {
private CharacterController controller;
private Rigidbody theRigidbody;
private Vector3 moveDistance;
void Start()
{
controller = GetComponent<CharacterController>();
theRigidbody = GetComponent<Rigidbody>();
moveDistance = Vector3.zero;
base.Start();
}
void FixedUpdate()
{
velocity += acceleration * Time.fixedDeltaTime;
if(velocity .sqrMagnitude >sqrMaxSpeed )
{
velocity = velocity.normalized * maxSpeed;
}
moveDistance = velocity * Time.fixedDeltaTime;
if(isPlanar )
{
velocity.y = 0;
moveDistance.y = 0;
}
if(controller !=null )
{
controller.SimpleMove(velocity);
}
else if(theRigidbody ==null ||theRigidbody .isKinematic )
{
transform.position += velocity;
}
else
{
theRigidbody.MovePosition(theRigidbody.position + moveDistance);
}
if(velocity .sqrMagnitude >0.00001)
{
Vector3 newForward = Vector3.Slerp(transform.forward, velocity, damping * Time.deltaTime);
if(isPlanar )
{
newForward.y = 0;
transform.forward = newForward;
}
}
//播放动画等等操纵
}
}
3,各种操作行为的基类,其中的Force()由它的派生类实现
using UnityEngine;
using System.Collections;
public class Steering : MonoBehaviour {
public float weight = 1;
void Start()
{
}
void Update()
{
}
public virtual Vector3 Force()
{
return Vector3.zero;
}
}
原谅我作为原创发表,这本书的确很好,比我之前看到的一个外国大神写的《unity3d人工智能编程》更加详细和全面,我会每天发表一篇博客,作为学习记录的.......
人笨,跟着各路大神有汤喝就足够了