Unity —有限状态机FSM系统(2)
程序员文章站
2024-03-19 18:31:10
...
FSM状态机
接上篇
PatrolState (巡逻状态)
PatrolState巡逻状态类,继承与FSMState(状态类),在巡逻状态时,当与主角距离比较近时,触发跟随状态,敌人进入跟随状态。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PatrolState : FSMState
{
private List<Transform> paths = new List<Transform>();
private int index = 0;
private Transform player;
public PatrolState(FSMSystem fsm) : base(fsm)
{
stateID = StateID.patrol;
Transform pathTransform = GameObject.Find("path").transform;
Transform[] chidren = pathTransform.GetComponentsInChildren<Transform>();
player = GameObject.Find("Player").transform;
foreach (var item in chidren)
{
if (item != pathTransform)
{
paths.Add(item);
}
}
}
public override void Act(GameObject npc)
{
npc.transform.LookAt(paths[index].position); //朝向
npc.transform.Translate(Vector3.forward * Time.deltaTime * 3);
if(Vector3.Distance(npc.transform.position,paths[index].position) < 1)
{
index++;
index %= paths.Count;
}
}
public override void Reason(GameObject npc)
{
if (Vector3.Distance(player.position, npc.transform.position) < 3)
{
fsm.PerformTransition(Transiton.SeePlayer);
}
}
}
ChaseState (跟随状态)
ChaseState 继承与FSMState(状态类),当敌人距离主角比较远的时候,触发巡逻状态,敌人回到巡逻状态。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChaseState : FSMState
{
private Transform player;
public ChaseState(FSMSystem fsm) : base(fsm)
{
stateID = StateID.Chase;
player = GameObject.Find("Player").transform;
}
public override void Act(GameObject npc)
{
npc.transform.LookAt(player.transform.position);
npc.transform.Translate(Vector3.forward * Time.deltaTime * 2);
}
public override void Reason(GameObject npc)
{
if (Vector3.Distance(player.position, npc.transform.position) > 6)
{
fsm.PerformTransition(Transiton.LostPlayer);
}
}
}
Enemy(敌人类)
Enemy 持有FSMSystem(状态管理类),通过Enemy来注册敌人的状态;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private FSMSystem fsm;
private void Awake()
{
InitFsm();
}
private void InitFsm()
{
fsm = new FSMSystem();
FSMState patroState = new PatrolState(fsm);
patroState.AddTransition(Transiton.SeePlayer, StateID.Chase);
FSMState chaseState = new ChaseState(fsm);
chaseState.AddTransition(Transiton.LostPlayer, StateID.patrol);
fsm.AddSatte(patroState);
fsm.AddSatte(chaseState);
}
private void Update()
{
fsm.Update(this.gameObject);
}
}
简单的效果
开始处于巡逻状态
靠近,敌人处于跟随主角状态
主角离远,回到巡逻状态
推荐阅读
-
Unity —有限状态机FSM系统(2)
-
FSM有限状态机学习及Unity3D案例讲解
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(24)-权限管理系统-将权限授权给角色
-
ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统之前端页面框架构建源码分享
-
ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统之前端页面框架构建源码分享
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(24)-权限管理系统-将权限授权给角色
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(26)-权限管理系统-分配角色给用户
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(29)-T4模版
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(27)-权限管理系统-分配用户给角色
-
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(26)-权限管理系统-分配角色给用户