Files
MouseTrailCollector/Assets/Stript/InGame/Bot/BotSpawner.cs
T
2026-10-20 15:21:09 +08:00

84 lines
2.2 KiB
C#

using System.Collections;
using UnityEngine;
// 一次只有一隻機器人,倒下後在隨機位置重生下一隻
// 掛在場景裡的空物件上,物件的位置就是生成範圍的中心
public class BotSpawner : MonoBehaviour
{
[Header("參照")]
[Tooltip("機器人 prefab (要有 BotBrain、BotHealth)")]
public BotBrain botPrefab;
[Tooltip("玩家 (機器人會面向它)")]
public Transform player;
[Header("生成範圍")]
[Tooltip("以這個物件為中心的半徑 (m),要比場地小,避免生成在牆裡")]
public float spawnRadius = 15f;
[Tooltip("離玩家的最小距離 (m)")]
public float minDistanceFromPlayer = 8f;
[Header("重生")]
[Tooltip("倒下後多久生成下一隻 (秒)")]
public float respawnDelay = 1.5f;
void Start()
{
Spawn();
}
void Spawn()
{
if (botPrefab == null) return;
BotBrain bot = Instantiate(botPrefab, PickSpawnPoint(), Quaternion.identity);
bot.target = player;
bot.areaCenter = transform.position;
bot.areaRadius = spawnRadius;
if (bot.TryGetComponent(out BotHealth health))
{
health.Died += OnBotDied;
}
}
void OnBotDied(BotHealth bot)
{
bot.Died -= OnBotDied;
StartCoroutine(RespawnAfterDelay());
}
IEnumerator RespawnAfterDelay()
{
yield return new WaitForSeconds(respawnDelay);
Spawn();
}
// 在範圍內隨機選點,盡量離玩家遠一點 ; 試幾次都太近就用最後一次的結果
Vector3 PickSpawnPoint()
{
Vector3 point = transform.position;
for (int i = 0; i < 20; i++)
{
Vector2 offset = Random.insideUnitCircle * spawnRadius;
point = transform.position + new Vector3(offset.x, 0f, offset.y);
if (player == null || Vector3.Distance(point, player.position) >= minDistanceFromPlayer)
{
break;
}
}
return point;
}
// 在 Scene 視窗畫出生成範圍,方便調整
void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, spawnRadius);
}
}