设置AI自动巡逻,追逐玩家时,分别为不同的移动速度,由于我们使用的自动寻路,所以在脚本中通过一个变量来设置navMeshAgent的速度,这样我们可以通过变量来自定义玩家和AI的速度,在移动逻辑部分,设置一个浮点值。通过浮点值来设置AI在巡逻时为行走状态,追逐玩家时为跑步状态。
移动部分因为动画资源和教程不同,所以使用了寻路时的速度/10,然后把这个速度传给动画状态机做动画的更新
Mover:
- using RPG.Combat;
- using RPG.Core;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- using UnityEngine.UI;
-
- //角色的移动
- namespace RPG.Movement
- {
-
- public class Mover : MonoBehaviour,IAction
- {
-
- [SerializeField] float maxSpeed = 6f;//最大速度
-
- private NavMeshAgent navMeshAgent;
-
- Animator animator;
- Health health;
- CapsuleCollider capsuleCollider;
-
- private void Start()
- {
- animator = GetComponent<Animator>();
- navMeshAgent = GetComponent<NavMeshAgent>();
- health = GetComponent<Health>();
- capsuleCollider = GetComponent<CapsuleCollider>();
- }
-
- private void Update()
- {
- if (health.IsDead())
- {
- capsuleCollider.enabled = false;//关闭碰撞
- navMeshAgent.enabled = false;//关闭寻路
- }
-
- UpdateAnimator();
- }
-
- /// <summary>
- /// 开始移动行为
- /// </summary>
- /// <param name="destination">移动的位置</param>
- public void StartMoveAction(Vector3 destination,float speedFraction)
- {
- GetComponent<ActionScheduler>().StartAction(this);
-
- MoveTo(destination,speedFraction);
- }
-
- /// <summary>
- /// 寻路移动到射线检测点
- /// </summary>
- /// <param name="hit"></param>
- public void MoveTo(Vector3 destination,float speedFraction)
- {
- navMeshAgent.destination = destination;//获取寻路目的地 = 射线碰撞的点
- navMeshAgent.speed = maxSpeed * Mathf.Clamp01(speedFraction);//设置速度的浮动值
- navMeshAgent.isStopped = false;
- }
-
- /// <summary>
- /// 停止寻路
- /// </summary>
- public void Cancel()
- {
- navMeshAgent.isStopped = true;
- }
-
-
-
- /// <summary>
- /// 动画更新
- /// </summary>
- private void UpdateAnimator()
- {
- Vector3 velocity = navMeshAgent.velocity;//创建寻路速度
- Vector3 localVelocity = transform.InverseTransformDirection(velocity);// 将世界向前变换到本地空间:
- float speed = localVelocity.z;
- //print("AI"+speed);
-
- animator.SetFloat("forwardSpeed", speed/10);
-
- }
-
-
- }
- }
复制代码
AIController:
复制代码 Fighter:
复制代码
|