FPS 之有限状态机和AI

using System.Collections.Generic;
using UnityEngine;
/*
使用射线扫描场景 例如:发现障碍物

有限状态机FSM:是一种代码结构,用于跟踪对象的当前状态,状态间存在明确定义的转换,且代码基于状态表现的不同
*/
public class WanderingAI : MonoBehaviour {
[SerializeField]
private GameObject fireballPrefab;
private GameObject _fireball;
public float speed = 3.0f;
public float obstacleRange = 5.0f;//对墙壁做出反应的距离
private bool _alive;
// Use this for initialization
void Start () {
_alive = true;
}

// Update is called once per frame
void Update () {
    if (_alive)//只有当角色存活时才移动
    {
        transform.Translate(0, 0, speed * Time.deltaTime);
        Ray ray = new Ray(transform.position, transform.forward);//和角色相同位置的射线 并且方向相同
        RaycastHit hit;
        //这个方法使用半径参数来决定在射线周围多远进行碰撞检测
        if (Physics.SphereCast(ray, 0.75f, out hit))
        {
            GameObject hitObject = hit.transform.gameObject;
            if (hitObject.GetComponent())
            {
                if (_fireball == null)
                {
                    _fireball = Instantiate(fireballPrefab) as GameObject;
                    //将火球放置在敌人前面并指向同一方向
                    _fireball.transform.position = transform.TransformPoint(Vector3.forward*1.5f);
                    _fireball.transform.rotation = transform.rotation;
                }
            }
            else if (hit.distance < obstacleRange)
            {
                float angle = Random.Range(-110, 110);
                transform.Rotate(0, angle, 0);
            }
        }
    }

}
//公有方法允许外部代码影响alive的值
public void SetAlive(bool alive)
{
    _alive = alive;
}

}

你可能感兴趣的:(unity3d,Unity3d手机)