添加AI失去对玩家的视线后,在原地怀疑一段时间后,自动回到初始站岗的位置。
AIController
- using RPG.Combat;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using RPG.Movement;
- using RPG.Core;
-
-
- namespace RPG.Control
- {
- //AI的控制
- public class AIController : MonoBehaviour
- {
- [SerializeField] float chaseDistance = 5f;// 设定追逐范围的距离
- [SerializeField] float suspicionTime = 4f;//丢失目标后原地等待时间
- float timeSinceLastSawPlayer = Mathf.Infinity;//最后一次看见玩家的时间
-
- Vector3 guardPosition;//默认位置
-
- Fighter fighter;
- Health health;
- Mover mover;
-
- GameObject player;
-
-
-
-
- private void Start()
- {
- fighter = GetComponent<Fighter>();
- health = GetComponent<Health>();
- player = GameObject.FindWithTag("Player");// 找到标签为“Player”的游戏对象
- mover = GetComponent<Mover>();
- guardPosition = transform.position;
- }
-
- private void Update()
- {
- if (health.IsDead()) return;//如果角色已经死亡,则跳出
-
-
- // 如果和玩家的距离小于设定的追逐范围 并且可以攻击玩家
- if (InAttackRangeOfPlayer()&& fighter.CanAttack(player))
- {
- timeSinceLastSawPlayer = 0;//设置为0
- AttackBehaviour();
-
- }
- else if(timeSinceLastSawPlayer < suspicionTime)//失去对玩家的视线后,怀疑时间
- {
- SuspicionBehaviour();
- }
- else//不在范围内
- {
- GuardBehaviour();
- }
-
- timeSinceLastSawPlayer += Time.deltaTime;
- }
-
- private void GuardBehaviour()//返回原站岗位置
- {
- mover.StartMoveAction(guardPosition);//回到初始的默认位置
- }
-
- private void SuspicionBehaviour()//丢失目标行为
- {
- GetComponent<ActionScheduler>().CancelCurrentAction();
- }
-
- private void AttackBehaviour()//攻击行为
- {
- fighter.Attack(player);//对玩家进行攻击
- }
-
- private bool InAttackRangeOfPlayer() // 检测是否在攻击范围内
- {
- float distanceToPlayer = Vector3.Distance(player.transform.position,transform.position); // 计算并返回玩家和当前对象之间的距离
- return distanceToPlayer < chaseDistance;//返回两者之间距离是否小于追逐距离
- }
-
- private void OnDrawGizmosSelected()//绘制线框球体
- {
- Gizmos.color = Color.yellow;
- Gizmos.DrawWireSphere(transform.position, chaseDistance);
- }
- }
- }
-
复制代码
|