简单的怪物跟随,

做一个简单的怪物跟随,只是简单的朝向,走向英雄,如果不在跟随范围时,怪物自己走动,走动的方向随机

估计这个跟随有障碍物就不行了 

怪物的动画用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 (-1f1f);
                    float y = Random.Range (-1f1f);

                    transform.LookAt (transform.position + new Vector3 (x0y));//让怪物朝向一个随机的方向
                }

            } 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.positionhero.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;    
            }

        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值