unity人物寻路结束后转换状态,如向左转,写出对应脚本C#,具体完整
时间: 2023-12-10 11:02:36 浏览: 28
以下是一个简单的示例脚本:
```csharp
using UnityEngine;
using UnityEngine.AI;
public class CharacterController : MonoBehaviour
{
public Transform target; // 目标位置
private NavMeshAgent navAgent;
private Animator anim;
private bool isRotating; // 是否正在旋转
private float rotateSpeed = 5.0f; // 旋转速度
void Start()
{
navAgent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
void Update()
{
// 设置目标位置
navAgent.SetDestination(target.position);
// 判断是否到达目标位置
if (navAgent.remainingDistance <= navAgent.stoppingDistance)
{
// 如果没有正在旋转,则开始旋转
if (!isRotating)
{
isRotating = true;
StartCoroutine(RotateCharacter());
}
}
}
// 旋转角色
IEnumerator RotateCharacter()
{
// 停止寻路
navAgent.isStopped = true;
// 计算目标方向
Vector3 targetDirection = target.position - transform.position;
targetDirection.y = 0;
// 计算旋转角度
float angle = Vector3.SignedAngle(transform.forward, targetDirection, Vector3.up);
// 播放向左转动画
if (angle < 0)
{
anim.SetBool("TurnLeft", true);
}
// 播放向右转动画
else
{
anim.SetBool("TurnRight", true);
}
// 旋转角色
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
while (Quaternion.Angle(transform.rotation, targetRotation) > 0.01f)
{
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotateSpeed);
yield return null;
}
// 结束旋转
anim.SetBool("TurnLeft", false);
anim.SetBool("TurnRight", false);
isRotating = false;
// 恢复寻路
navAgent.isStopped = false;
}
}
```
在该脚本中,我们使用 NavMeshAgent 组件来实现人物的寻路功能,并利用 Animator 组件来播放人物的转身动画。当人物到达目标位置后,我们会调用一个协程来旋转人物,并播放相应方向的动画。在旋转过程中,我们会停止人物的寻路,并手动控制人物的旋转。旋转完成后,我们会恢复人物的寻路,并结束转身动画的播放。