66 lines
1.9 KiB
C#
66 lines
1.9 KiB
C#
using UnityEngine;
|
|
using UnityEngine.AI;
|
|
|
|
[RequireComponent(typeof(NavMeshAgent))]
|
|
public class SlimeMovement : MonoBehaviour
|
|
{
|
|
public float changeTargetInterval = 3f; // 随机移动间隔
|
|
public float rotationSpeed = 5f; // 旋转速度
|
|
public float moveRadius = 10f; // 活动范围
|
|
public Animator playAnimator;
|
|
public bool isStop;
|
|
|
|
private NavMeshAgent agent;
|
|
private Vector3 startPos;
|
|
private float timer;
|
|
|
|
void Start()
|
|
{
|
|
agent = GetComponent<NavMeshAgent>();
|
|
agent.updateRotation = false; // 禁用 NavMeshAgent 的自动旋转
|
|
startPos = transform.position;
|
|
isStop = false;
|
|
float playTime=Random.Range(0f,1.5f);
|
|
PickNewDestination();
|
|
}
|
|
|
|
public void Stop()
|
|
{
|
|
isStop = true;
|
|
agent.enabled = false;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if(isStop)
|
|
return;
|
|
timer += Time.deltaTime;
|
|
|
|
// 如果到达目标或间隔时间到,选择新的目标
|
|
if (!agent.pathPending && agent.remainingDistance <= 0.5f || timer >= changeTargetInterval)
|
|
{
|
|
PickNewDestination();
|
|
timer = 0f;
|
|
}
|
|
|
|
// 平滑朝向目标方向旋转
|
|
Vector3 direction = agent.velocity;
|
|
if (direction.sqrMagnitude > 0.1f)
|
|
{
|
|
Quaternion targetRotation = Quaternion.LookRotation(direction.normalized);
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
|
|
}
|
|
}
|
|
|
|
void PickNewDestination()
|
|
{
|
|
Vector2 randomCircle = Random.insideUnitCircle * moveRadius;
|
|
Vector3 randomPos = startPos + new Vector3(randomCircle.x, 0, randomCircle.y);
|
|
NavMeshHit hit;
|
|
|
|
if (NavMesh.SamplePosition(randomPos, out hit, 2.0f, NavMesh.AllAreas))
|
|
{
|
|
agent.SetDestination(hit.position);
|
|
}
|
|
}
|
|
} |