using System; using System.Collections.Generic; using GazeLab.Combat; using GazeLab.Core; using GazeLab.Data; using UnityEngine; namespace GazeLab.Entities { public sealed class EnemyShipController : MonoBehaviour { public static readonly List ActiveShips = new List(); public static void RecycleAllActive() { var ships = ActiveShips.ToArray(); for (int i = 0; i < ships.Length; i++) { if (ships[i] != null && ships[i].gameObject != null) { Destroy(ships[i].gameObject); } } ActiveShips.Clear(); } public EnemyArchetypeDefinition archetype; public bool isWaveBossLead; public float roleScaleMultiplier = 1f; private DamageableEntity damageable; private SpriteRenderer hullRenderer; private WaveCatalog catalogRef; private readonly List mountedTurrets = new List(); private float currentWorldScale = 1f; private float spawnTime; private float strafePhaseOffset; private Vector3 anchorCenterPos; private bool hasReachedStandoff; private float nextDiveTime; private bool isDiving; private float diveProgress; public DamageableEntity ShipDamageable => damageable; public static event Action OnEnemyShipSpawned; public static event Action OnEnemyShipDestroyed; public static EnemyShipController Spawn( EnemyArchetypeDefinition def, WaveCatalog catalog, Vector3 spawnPos, bool isBossLead, float roleScaleMult, float hpMult, float dmgMult, float worldScale) { if (def == null) return null; GameObject go = new GameObject($"Ship_{def.archetypeId}{(isBossLead ? "_BOSS" : "")}"); go.transform.position = spawnPos; var ctrl = go.AddComponent(); ctrl.Initialize(def, catalog, isBossLead, roleScaleMult, hpMult, dmgMult, worldScale); return ctrl; } private void OnEnable() { if (!ActiveShips.Contains(this)) ActiveShips.Add(this); } private void OnDisable() { ActiveShips.Remove(this); if (damageable != null) { damageable.OnDamaged -= HandleDamaged; damageable.OnKilled -= HandleKilled; } } private void Initialize( EnemyArchetypeDefinition def, WaveCatalog catalog, bool bossLead, float roleScale, float hpMult, float dmgMult, float worldScale) { archetype = def; catalogRef = catalog; isWaveBossLead = bossLead; roleScaleMultiplier = Mathf.Max(0.35f, roleScale); spawnTime = Time.time; strafePhaseOffset = UnityEngine.Random.Range(0f, Mathf.PI * 2f); nextDiveTime = Time.time + def.diveIntervalSeconds; float targetStandoffY = -3.4f + def.hoverDistance * Mathf.Lerp(1f, worldScale, 0.35f); targetStandoffY = Mathf.Clamp(targetStandoffY, -0.8f, 3.3f); anchorCenterPos = new Vector3(Mathf.Clamp(transform.position.x, -3.5f, 3.5f), targetStandoffY, 0f); hullRenderer = gameObject.AddComponent(); hullRenderer.sprite = def.healthySprite; hullRenderer.color = def.hullTint; hullRenderer.sortingOrder = bossLead ? 9 : 7; damageable = gameObject.AddComponent(); damageable.category = bossLead ? EntityCategory.BossHull : EntityCategory.EnemyShip; damageable.displayName = bossLead ? $"BOSS: {def.displayName}" : def.displayName; damageable.mainSpriteRenderer = hullRenderer; int neededChains = bossLead ? Mathf.Max(2, def.requiredHarpoonChains) : def.requiredHarpoonChains; damageable.InitializeStats( def.maxHull * hpMult, def.maxShield * hpMult, def.shieldRegenPerSec, def.isArmored, def.armorDamageReduction, neededChains, def.shieldProfile); damageable.OnDamaged += HandleDamaged; damageable.OnKilled += HandleKilled; // Point nose (+X) downward (-90 deg) initially toward the Space Station transform.rotation = Quaternion.Euler(0f, 0f, -90f); BuildTurretHardpoints(def, dmgMult, worldScale); ApplyWorldScale(worldScale); OnEnemyShipSpawned?.Invoke(this); } private void BuildTurretHardpoints(EnemyArchetypeDefinition def, float dmgMult, float worldScale) { if (def.hardpoints == null) return; for (int i = 0; i < def.hardpoints.Length; i++) { EnemyHardpointSlot slot = def.hardpoints[i]; if (slot.weapon == null) continue; GameObject slotGo = new GameObject($"Hardpoint_{i}_{slot.partName}"); slotGo.transform.SetParent(transform, false); slotGo.transform.localPosition = new Vector3(slot.localOffset.x, slot.localOffset.y, 0f); DamageableEntity turretOwner = damageable; if (slot.isDestructibleSubPart) { var partDmg = slotGo.AddComponent(); partDmg.category = EntityCategory.BossSubTurret; partDmg.displayName = $"{def.displayName} - {slot.partName}"; partDmg.targetHitRadius = 0.42f * worldScale; partDmg.InitializeStats(slot.subPartMaxHealth, 0f, 0f, def.isArmored, def.armorDamageReduction * 0.5f, 1, null); int scrapBonus = slot.bonusScrapOnBreak; int goldBonus = slot.bonusGoldOnBreak; partDmg.OnKilled += (subEnt, proj) => { ShockwaveExplosionController.Spawn(subEnt.transform.position, null, null, 0.7f * currentWorldScale, new Color(1f, 0.55f, 0.2f)); DamageableEntity.OnSpawnFloatingText?.Invoke(subEnt.transform.position + Vector3.up * 0.3f, $"{slot.partName.ToUpper()} DESTROYED!", new Color(1f, 0.8f, 0.25f), 1.1f); SpawnRewardPickups(subEnt.transform.position, new ResourceCost(scrapBonus, goldBonus, 0)); Destroy(subEnt.gameObject); }; turretOwner = partDmg; } var turret = slotGo.AddComponent(); float turretScale = slot.turretScaleMultiplier > 0.05f ? slot.turretScaleMultiplier : 0.65f; turret.ConfigureTurret( slot.weapon, playerOwned: false, autoFire: true, scaleMult: turretScale, defaultRestAngle: -90f, owner: turretOwner, sortingOrder: hullRenderer.sortingOrder + 2); turret.SetGlobalBuffs(dmgMult, 1f, worldScale); if (slot.isDestructibleSubPart && turretOwner != damageable) { turretOwner.mainSpriteRenderer = turret.weaponSpriteRenderer; } mountedTurrets.Add(turret); } } public void ApplyWorldScale(float stationWorldScale) { currentWorldScale = Mathf.Clamp(stationWorldScale, 0.25f, 1.5f); float combinedScale = (archetype != null ? archetype.baseVisualScale : 0.35f) * roleScaleMultiplier * currentWorldScale; transform.localScale = Vector3.one * combinedScale; if (damageable != null) { float radiusFactor = isWaveBossLead ? 2.1f : 1.55f; damageable.targetHitRadius = Mathf.Max(0.28f, combinedScale * radiusFactor); } for (int i = 0; i < mountedTurrets.Count; i++) { if (mountedTurrets[i] != null) { mountedTurrets[i].worldProjectileScale = currentWorldScale; } } } private void Update() { if (damageable == null || !damageable.IsAlive || archetype == null) return; float dt = Time.deltaTime; Vector3 stationPos = SpaceStationController.Instance != null ? SpaceStationController.Instance.transform.position : new Vector3(0f, -3.6f, 0f); // 1. Check if immobilized and reeled in by the Station's Harpoon Grapple Chain! if (damageable.IsHarpoonImmobilized) { Vector3 dirFromStation = (transform.position - stationPos); dirFromStation.z = 0f; if (dirFromStation.sqrMagnitude < 0.01f) dirFromStation = Vector3.up; Vector3 pulledPos = stationPos + dirFromStation.normalized * damageable.harpoonTargetDistance; pulledPos.y = Mathf.Max(pulledPos.y, stationPos.y + 1.45f); transform.position = Vector3.MoveTowards(transform.position, pulledPos, damageable.harpoonPullSpeed * dt); anchorCenterPos = transform.position; } else { UpdateFlightManeuvers(dt, stationPos); } // 2. Smoothly orient ship nose (+X) toward the Space Station Vector3 toStation = stationPos - transform.position; toStation.z = 0f; if (toStation.sqrMagnitude > 0.01f) { float targetAngle = Mathf.Atan2(toStation.y, toStation.x) * Mathf.Rad2Deg; float curAngle = transform.eulerAngles.z; float nextAngle = Mathf.MoveTowardsAngle(curAngle, targetAngle, 140f * dt); transform.rotation = Quaternion.Euler(0f, 0f, nextAngle); } } private void UpdateFlightManeuvers(float dt, Vector3 stationPos) { float speedMult = damageable.MovementSpeedMultiplier; if (speedMult <= 0.01f) return; if (!hasReachedStandoff) { transform.position = Vector3.MoveTowards(transform.position, anchorCenterPos, archetype.approachSpeed * speedMult * dt); if ((transform.position - anchorCenterPos).sqrMagnitude <= 0.05f) { hasReachedStandoff = true; spawnTime = Time.time; } return; } float t = (Time.time - spawnTime) * archetype.strafeSpeed * speedMult + strafePhaseOffset; float amp = archetype.strafeAmplitude * Mathf.Lerp(1f, currentWorldScale, 0.3f); float maxX = Mathf.Max(3.5f, CameraViewportService.HalfWidth - 0.9f); Vector3 desiredPos = anchorCenterPos; switch (archetype.strafePattern) { case EnemyStrafePattern.SineWeave: desiredPos.x = Mathf.Clamp(anchorCenterPos.x + Mathf.Sin(t) * amp, -maxX, maxX); desiredPos.y = anchorCenterPos.y + Mathf.Cos(t * 1.7f) * 0.35f; break; case EnemyStrafePattern.PingPongHorizontal: desiredPos.x = Mathf.PingPong(t * 1.5f, maxX * 1.6f) - maxX * 0.8f; break; case EnemyStrafePattern.OrbitArc: desiredPos.x = Mathf.Clamp(Mathf.Sin(t * 0.8f) * (amp * 1.3f), -maxX, maxX); desiredPos.y = anchorCenterPos.y + Mathf.Sin(t * 1.6f) * 0.55f; break; case EnemyStrafePattern.PeriodicDiveRun: if (!isDiving && Time.time >= nextDiveTime) { isDiving = true; diveProgress = 0f; } if (isDiving) { diveProgress += dt * 0.65f * speedMult; float diveOffset = Mathf.Sin(diveProgress * Mathf.PI) * 1.9f; desiredPos.x = Mathf.Clamp(anchorCenterPos.x + Mathf.Sin(t) * amp, -maxX, maxX); desiredPos.y = Mathf.Max(stationPos.y + 1.5f, anchorCenterPos.y - diveOffset); if (diveProgress >= 1f) { isDiving = false; nextDiveTime = Time.time + archetype.diveIntervalSeconds; } } else { desiredPos.x = Mathf.Clamp(anchorCenterPos.x + Mathf.Sin(t) * amp, -maxX, maxX); } break; case EnemyStrafePattern.HeavyStandoff: desiredPos.x = Mathf.Clamp(anchorCenterPos.x + Mathf.Sin(t * 0.55f) * (amp * 0.75f), -maxX, maxX); break; } transform.position = Vector3.Lerp(transform.position, desiredPos, dt * 3.5f); } private void HandleDamaged(DamageableEntity ent, float dmg, Vector3 hitPos, WeaponFamily family) { if (hullRenderer == null || archetype == null) return; // Swap Hull Sprites across Healthy (>= 66%) -> Damaged (33-65%) -> Broken (< 33%) float ratio = ent.HullRatio; if (ratio < 0.34f && archetype.brokenSprite != null) { hullRenderer.sprite = archetype.brokenSprite; } else if (ratio < 0.67f && archetype.damagedSprite != null) { hullRenderer.sprite = archetype.damagedSprite; } else if (archetype.healthySprite != null) { hullRenderer.sprite = archetype.healthySprite; } } private void HandleKilled(DamageableEntity ent, ProjectileDefinition killingProj) { Vector3 pos = transform.position; float expScale = (isWaveBossLead ? 1.75f : 1.05f) * currentWorldScale; ShockwaveExplosionController.Spawn( pos, killingProj != null ? killingProj.explosionSprite : null, killingProj != null ? killingProj.explosionCentroidProfile : null, expScale, new Color(1f, 0.65f, 0.25f)); if (archetype != null) { ResourceCost drop = archetype.guaranteedDrop; if (isWaveBossLead) { drop.scrap = Mathf.Max(drop.scrap * 2, 18); drop.gold = Mathf.Max(drop.gold + 3, 4); } SpawnRewardPickups(pos, drop); if (UnityEngine.Random.value <= archetype.bonusRareDropChance) { SpawnRewardPickups(pos, new ResourceCost(0, 1, 1)); } } OnEnemyShipDestroyed?.Invoke(this); Destroy(gameObject); } private void SpawnRewardPickups(Vector3 pos, ResourceCost drop) { Transform stTrans = SpaceStationController.Instance != null ? SpaceStationController.Instance.transform : null; if (drop.scrap > 0) { int chunks = Mathf.Clamp(drop.scrap / 4 + 1, 1, 4); int perChunk = Mathf.Max(1, Mathf.CeilToInt((float)drop.scrap / chunks)); for (int i = 0; i < chunks; i++) { Vector2 vel = UnityEngine.Random.insideUnitCircle.normalized * UnityEngine.Random.Range(0.9f, 2.4f); ResourcePickupController.Spawn(ResourceType.Scrap, perChunk, AsteroidController.PickLootSprite(catalogRef, ResourceType.Scrap), pos, vel, stTrans, currentWorldScale); } } if (drop.gold > 0) { for (int i = 0; i < Mathf.Min(3, drop.gold); i++) { int val = i == 0 ? Mathf.Max(1, drop.gold - Mathf.Min(2, drop.gold - 1)) : 1; Vector2 vel = UnityEngine.Random.insideUnitCircle.normalized * UnityEngine.Random.Range(1.0f, 2.5f); ResourcePickupController.Spawn(ResourceType.Gold, val, AsteroidController.PickLootSprite(catalogRef, ResourceType.Gold), pos, vel, stTrans, currentWorldScale); } } if (drop.uranium > 0) { for (int i = 0; i < Mathf.Min(3, drop.uranium); i++) { int val = i == 0 ? Mathf.Max(1, drop.uranium - Mathf.Min(2, drop.uranium - 1)) : 1; Vector2 vel = UnityEngine.Random.insideUnitCircle.normalized * UnityEngine.Random.Range(1.1f, 2.6f); ResourcePickupController.Spawn(ResourceType.Uranium, val, AsteroidController.PickLootSprite(catalogRef, ResourceType.Uranium), pos, vel, stTrans, currentWorldScale); } } } } }