unity实现敌人的功能:正常状态下站立,如果过了三秒就开始巡逻,到达了指定的目标点后回到正常状态站立。一共有制定的三个目标点,如果走到第一个接下来就走第二个,如果走到第二个接下来就走第三个,如果走到第三个接下来就走第一个。的脚本
时间: 2024-03-22 13:38:45 浏览: 80
好的,这是一个基于时间的简单实现,可以使用Unity的协程来实现。以下是一个可能的脚本代码示例:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public Transform[] targetPoints; // 目标点数组
public float patrolTime = 3f; // 巡逻时间
public float standTime = 1f; // 站立时间
private int currentTargetIndex = 0; // 当前目标点索引
private bool isPatrolling = false; // 是否在巡逻中
void Start()
{
// 开始时站立
Stand();
}
void Update()
{
// 如果不在巡逻中,就检查是否需要开始巡逻
if (!isPatrolling)
{
// 如果站立时间到了,就开始巡逻
if (Time.timeSinceLevelLoad >= standTime)
{
StartCoroutine(Patrol());
}
}
}
IEnumerator Patrol()
{
// 标记为正在巡逻
isPatrolling = true;
// 到达目标点前先站立一段时间
yield return new WaitForSeconds(standTime);
// 移向当前目标点
Transform targetPoint = targetPoints[currentTargetIndex];
while (transform.position != targetPoint.position)
{
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, Time.deltaTime);
yield return null;
}
// 到达目标点后站立一段时间,然后继续巡逻
yield return new WaitForSeconds(standTime);
currentTargetIndex = (currentTargetIndex + 1) % targetPoints.Length;
isPatrolling = false;
Stand();
}
void Stand()
{
// 停止移动并等待一段时间
transform.position = transform.position;
StartCoroutine(StandCoroutine());
}
IEnumerator StandCoroutine()
{
yield return new WaitForSeconds(Random.Range(0, patrolTime));
}
}
```
这个脚本假设目标点是在同一平面上的,它通过比较当前位置和目标点位置的距离来判断是否到达目标点。如果要在不同平面上使用,需要将比较改为使用碰撞盒或触发器。
阅读全文
相关推荐


















