Files
FORT-BO/Assets/CONTENT/FEATURES/MapRadar/MapTargetController.cs
T
Henjke d559ab338a Map
Controller
Coordinates
Target System
Crosshair System
Radar System
2026-08-13 18:42:41 +05:00

114 lines
3.3 KiB
C#

using System.Collections.Generic;
using UnityEngine;
[DisallowMultipleComponent]
public sealed class MapTargetController : MonoBehaviour
{
[Header("Target Settings")]
[SerializeField, Min(0)] private int targetCount = 5;
[SerializeField, Min(0f)] private float targetMovementSpeed = 1f;
private readonly List<MapTarget> targets = new();
private MapCoordinateSystem coordinateSystem;
private MapTarget targetPrefab;
private Transform targetParent;
private bool isConfigured;
public IReadOnlyList<MapTarget> Targets => targets;
public int TargetCount => targetCount;
public float TargetMovementSpeed => targetMovementSpeed;
private void OnValidate()
{
targetCount = Mathf.Max(0, targetCount);
targetMovementSpeed = Mathf.Max(0f, targetMovementSpeed);
}
public void Configure(
MapCoordinateSystem newCoordinateSystem,
MapTarget newTargetPrefab,
Transform newTargetParent)
{
coordinateSystem = newCoordinateSystem;
targetPrefab = newTargetPrefab;
targetParent = newTargetParent != null ? newTargetParent : transform;
isConfigured = coordinateSystem != null &&
coordinateSystem.HasValidCorners() &&
targetPrefab != null;
}
public void CreateAndPlaceTargets()
{
if (!isConfigured)
{
Debug.LogWarning("Target system is not configured.", this);
return;
}
RegisterExistingTargets();
while (targets.Count < targetCount)
{
MapTarget target = Instantiate(targetPrefab, targetParent);
target.name = $"Target_{targets.Count + 1}";
targets.Add(target);
}
while (targets.Count > targetCount)
{
int lastIndex = targets.Count - 1;
MapTarget target = targets[lastIndex];
targets.RemoveAt(lastIndex);
if (target != null)
Destroy(target.gameObject);
}
for (int index = 0; index < targets.Count; index++)
{
MapTarget target = targets[index];
if (target == null)
continue;
target.Configure(
coordinateSystem,
GetRandomCoordinates(),
targetMovementSpeed,
Random.insideUnitCircle.normalized);
target.SetVisualsVisible(false);
}
}
public void SetTargetVisualsVisible(bool isVisible)
{
foreach (MapTarget target in targets)
{
if (target != null)
target.SetVisualsVisible(isVisible);
}
}
public MapTarget GetTarget(int index)
{
return index >= 0 && index < targets.Count ? targets[index] : null;
}
private void RegisterExistingTargets()
{
targets.Clear();
MapTarget[] existingTargets = targetParent.GetComponentsInChildren<MapTarget>(true);
foreach (MapTarget target in existingTargets)
{
if (target != null && !targets.Contains(target))
targets.Add(target);
}
}
private static Vector2 GetRandomCoordinates()
{
float maximum = MapCoordinateSystem.CoordinateMaximum;
return new Vector2(Random.Range(0f, maximum), Random.Range(0f, maximum));
}
}