做一个简单的怪物跟随,只是简单的朝向,走向英雄,如果不在跟随范围时,怪物自己走动,走动的方向随机
估计这个跟随有障碍物就不行了
怪物的动画用Animation
用角色控制器控制怪物
using UnityEngine;
using System.Collections;
public class AItest : MonoBehaviour {
//[HideInInspector]
public Transform hero;//要跟随英雄
private CharacterController con;//怪物的角色控制器
private Animation ani;//旧版动画
public float followDis = 10f;//达到这个距离开始跟随
public float attackDis = 2f;//达到这个距离开始攻击
public float thinkTime = 3f;//思考的时间
public float currentThinkTime = 0f;//记录思考的时间
public float walkTime = 5f;//走的时间
public float currentWalkTime = 0;//记录走的时间
private bool isAttact = false;//是否攻击
void Start () {
con = GetComponent<CharacterController> ();//得到觉得控制器
ani = GetComponent<Animation> ();//得到动画
}
void Update () {
Think ();//思考
Attack ();//攻击
}
//思考
void Think()
{
if (!isAttact)//如果不攻击,就开始走
{
currentWalkTime += Time.deltaTime;//开始记录走的时间
if (currentWalkTime >= walkTime) {//当走的时间大于设定的时间时
ani.CrossFade ("Idle");//怪物进入idle状态
currentThinkTime += Time.deltaTime;//记录思考的时间
if (currentThinkTime >= thinkTime) {//当思考时间大于开始设定的时间时
currentWalkTime = 0f;
currentThinkTime = 0f;
float x = Random.Range (-1f, 1f);
float y = Random.Range (-1f, 1f);
transform.LookAt (transform.position + new Vector3 (x, 0, y));//让怪物朝向一个随机的方向
}
} else {//当怪物走的时间
ani.CrossFade ("Run");
Vector3 direction = transform.TransformDirection (Vector3.forward);
direction.y -= 9.8f;
con.Move (direction * 1f * Time.deltaTime);
}
}
}
//攻击
void Attack()
{
if (hero == null) {//如果英雄不存在直接返回
return;
}
if (Vector3.Distance (transform.position, hero.position) <= followDis)//跟随距离
{
transform.LookAt(hero);
if(Vector3.Distance(transform.position,hero.position) > attackDis)
{
isAttact = false;//大于攻击距离后不攻击
ani.CrossFade("Run");//开始执行走的动画表示跟随
Vector3 dierction = transform.TransformDirection(Vector3.forward);
dierction.y -= 9.8f;
con.Move(dierction * 1f * Time.deltaTime);
}
else//小于攻击距离后开始攻击
{
ani.CrossFade("Attack");
isAttact = true;
}
}
}
}