# 3. TD Capstone Enemies and Towers Part of [[Tower Defense Capstone]]. Previous: [[2. TD Capstone Rules Core Economy Paths and Waves]]. Next: [[4. TD Capstone Building Upgrading and the HUD]]. ## 3.1 Definitions Everything you'll tune lives in three ScriptableObject types, all in one file. `Assets/TowerDefense/Runtime/TdDefinitions.cs`: **`TdDefinitions.cs`** ```csharp using UnityEngine; /// <summary>One enemy type. Assets > Create > Tower Defense > Enemy.</summary> [CreateAssetMenu(menuName = "Tower Defense/Enemy", fileName = "Enemy")] public sealed class EnemyDefinition : ScriptableObject { public string id = "runner"; public TdEnemy prefab; [Min(1f)] public float health = 30f; [Min(0.1f)] public float speed = 3f; // metres per second along the path [Min(0)] public int reward = 5; // gold on kill [Min(1)] public int leakDamage = 1; // lives lost on reaching the end [Range(0f, 0.9f)] public float armor; // fraction of each hit ignored } /// <summary>One tower type with its upgrade levels. Assets > Create > Tower Defense > Tower.</summary> [CreateAssetMenu(menuName = "Tower Defense/Tower", fileName = "Tower")] public sealed class TowerDefinition : ScriptableObject { [System.Serializable] public struct Level { [Min(0)] public int cost; // build cost for level 0, upgrade cost after that [Min(0.5f)] public float range; [Min(0.05f)] public float shotsPerSecond; [Min(0f)] public float damage; [Min(0f)] public float splashRadius; // 0 = single target [Range(0f, 0.9f)] public float slow; // fraction of speed removed while slowed [Min(0f)] public float slowSeconds; } public string displayName = "Bolt"; public TdTower prefab; public Level[] levels = { new Level { cost = 50, range = 4f, shotsPerSecond = 2f, damage = 10f }, new Level { cost = 40, range = 4.5f, shotsPerSecond = 2.5f, damage = 14f }, new Level { cost = 70, range = 5f, shotsPerSecond = 3f, damage = 20f }, }; public int BuildCost => levels.Length > 0 ? levels[0].cost : 0; } /// <summary>A wave: groups that spawn in parallel. Assets > Create > Tower Defense > Wave.</summary> [CreateAssetMenu(menuName = "Tower Defense/Wave", fileName = "Wave")] public sealed class WaveDefinition : ScriptableObject { public SpawnGroup[] groups = { new SpawnGroup { enemyId = "runner", count = 8, interval = 0.8f, delay = 0f } }; [Min(0)] public int clearBonus = 25; } ``` - **`EnemyDefinition`** has an `id` that waves refer to, its prefab, health, speed, gold reward, how many lives it costs on leaking, and **armour**, the fraction of each hit it ignores. - **`TowerDefinition`** has a list of **levels**. Level 0's `cost` is the build price; each later level's `cost` is that upgrade's price. A level carries range, fire rate, damage, splash radius and slow. - **`WaveDefinition`** is a list of `SpawnGroup`s (part 2) plus a gold bonus for clearing it. Create the assets in `Assets/TowerDefense/Data/` with **Assets > Create > Tower Defense**. **Enemies:** | Asset | id | Health | Speed | Reward | Leak | Armour | |---|---|---|---|---|---|---| | Runner | `runner` | 30 | 3.0 | 5 | 1 | 0 | | Swarm | `swarm` | 12 | 2.4 | 2 | 1 | 0 | | Tank | `tank` | 220 | 1.2 | 25 | 3 | 0.4 | **Towers** (cost / range / shots per second / damage / splash / slow fraction / slow seconds): | Tower | Level 1 | Level 2 | Level 3 | |---|---|---|---| | Bolt | 50 / 4 / 2 / 10 / 0 | 40 / 4.5 / 2.5 / 14 / 0 | 70 / 5 / 3 / 20 / 0 | | Mortar | 90 / 6 / 0.5 / 35 / 2 | 70 / 6.5 / 0.5 / 55 / 2.2 | 120 / 7 / 0.6 / 80 / 2.5 | | Frost | 70 / 3.5 / 1.5 / 3 / 1.5 / 0.4 / 1.5 | 50 / 4 / 1.5 / 4 / 1.8 / 0.5 / 1.5 | 80 / 4.5 / 2 / 6 / 2 / 0.6 / 2 | The Bolt's defaults are already in `TowerDefinition`'s field initialisers. ## 3.2 TdEnemy `Assets/TowerDefense/Runtime/TdEnemy.cs`: **`TdEnemy.cs`** ```csharp using System; using UnityEngine; /// <summary> /// Walks the path by distance (no physics, no NavMesh), takes damage and slows, pays out on death /// and costs lives on reaching the end. Its <see cref="Progress"/> is what towers target by. /// </summary> public sealed class TdEnemy : MonoBehaviour { [SerializeField] Transform healthBar; // optional: a quad scaled on X EnemyDefinition _def; TdGame _game; float _slowUntil, _slowFactor = 1f; public EnemyDefinition Definition => _def; public float Progress { get; private set; } public float Health { get; private set; } public bool Alive => Health > 0f && _game != null; public event Action<TdEnemy> Removed; // died or leaked; the spawner pools it public void Init(EnemyDefinition def, TdGame game) { _def = def; _game = game; Health = def.health; Progress = 0f; _slowFactor = 1f; _slowUntil = 0f; Place(); } public void Damage(float amount) { if (!Alive) return; Health -= amount * (1f - _def.armor); if (Health <= 0f) { _game.Economy.Earn(_def.reward); Remove(); } } public void Slow(float fraction, float seconds) { if (!Alive || fraction <= 0f) return; _slowFactor = Mathf.Min(_slowFactor, 1f - fraction); // strongest slow wins, slows don't stack _slowUntil = Mathf.Max(_slowUntil, Time.time + seconds); } void Update() { if (!Alive) return; if (Time.time >= _slowUntil) _slowFactor = 1f; Progress += _def.speed * _slowFactor * Time.deltaTime; if (Progress >= _game.Path.Length) { _game.Economy.Leak(_def.leakDamage); Remove(); return; } Place(); if (healthBar != null) healthBar.localScale = new Vector3(Mathf.Clamp01(Health / _def.health), healthBar.localScale.y, healthBar.localScale.z); } void Place() { var (x, z, dx, dz) = _game.Path.Sample(Progress); transform.SetPositionAndRotation(new Vector3(x, _game.PathHeight, z), Quaternion.LookRotation(new Vector3(dx, 0f, dz))); } void Remove() { Health = 0f; _game = null; Removed?.Invoke(this); } } ``` How it works: - **`Init` resets everything** because enemies come from a pool (part 4). A pooled object keeps whatever state it had when it was released, so anything you forget to reset leaks into the next life. - **Movement** is one line: progress += speed × slow × deltaTime. Then `Place` asks the path for a position and a facing. - **Armour** scales incoming damage: a Bolt's 10 becomes 6 on a tank. That's why tanks push you toward the Mortar, whose bigger hits suffer the same 40% but kill far faster. - **Slows don't stack.** The strongest active slow wins, and its timer extends to the latest expiry. Stacking slows (two Frost towers giving 0.4 + 0.4 = 80%) is the classic tower defense balance break. - **`Remove` clears `_game` first.** That makes `Alive` false immediately, so a splash shell that hits the same enemy twice, or two towers firing in the same frame, can't pay out the reward twice. - **`Removed`** is how `TdGame` learns to return the enemy to its pool and take it off the live list. ## 3.3 TdTower `Assets/TowerDefense/Runtime/TdTower.cs`: **`TdTower.cs`** ```csharp using System.Collections.Generic; using UnityEngine; /// <summary> /// Picks a target among enemies in range with <see cref="TargetPicker"/>, turns its head, and fires /// on a cooldown. Hits are instant (with a short tracer) so the tower never misses: in tower defense, /// the interesting decisions are placement and targeting, not ballistics. /// </summary> public sealed class TdTower : MonoBehaviour { [SerializeField] Transform head; // yaws toward the target [SerializeField] Transform muzzle; [SerializeField] LineRenderer tracer; [SerializeField] Transform rangeIndicator; // optional flat disc, scaled to the range readonly List<TargetInfo> _infos = new List<TargetInfo>(); readonly List<TdEnemy> _inRange = new List<TdEnemy>(); TdGame _game; float _cooldown, _tracerOff; public TowerDefinition Definition { get; private set; } public int LevelIndex { get; private set; } public int TotalSpent { get; private set; } public Vector2Int Cell { get; private set; } public TargetMode Mode { get; set; } = TargetMode.First; public TowerDefinition.Level Stats => Definition.levels[LevelIndex]; public bool CanUpgrade => LevelIndex + 1 < Definition.levels.Length; public int UpgradeCost => CanUpgrade ? Definition.levels[LevelIndex + 1].cost : 0; public void Init(TowerDefinition def, TdGame game, Vector2Int cell) { Definition = def; _game = game; Cell = cell; LevelIndex = 0; TotalSpent = def.BuildCost; ShowRange(false); if (tracer != null) tracer.enabled = false; } public bool TryUpgrade() { if (!CanUpgrade || !_game.Economy.TrySpend(UpgradeCost)) return false; TotalSpent += UpgradeCost; LevelIndex++; if (rangeIndicator != null && rangeIndicator.gameObject.activeSelf) ShowRange(true); return true; } public void ShowRange(bool on) { if (rangeIndicator == null) return; rangeIndicator.gameObject.SetActive(on); var d = Stats.range * 2f; rangeIndicator.localScale = new Vector3(d, rangeIndicator.localScale.y, d); } void Update() { if (_game == null) return; if (tracer != null && tracer.enabled && Time.time >= _tracerOff) tracer.enabled = false; _cooldown -= Time.deltaTime; var target = FindTarget(); if (target == null) return; if (head != null) { var flat = target.transform.position - head.position; flat.y = 0f; if (flat.sqrMagnitude > 0.0001f) head.rotation = Quaternion.LookRotation(flat); } if (_cooldown > 0f) return; _cooldown = 1f / Stats.shotsPerSecond; Fire(target); } TdEnemy FindTarget() { _infos.Clear(); _inRange.Clear(); var rangeSq = Stats.range * Stats.range; var p = transform.position; foreach (var e in _game.Enemies) { if (!e.Alive) continue; var d = e.transform.position - p; d.y = 0f; if (d.sqrMagnitude > rangeSq) continue; _inRange.Add(e); _infos.Add(new TargetInfo { progress = e.Progress, health = e.Health, distanceSq = d.sqrMagnitude }); } var i = TargetPicker.Pick(_infos, Mode); return i < 0 ? null : _inRange[i]; } void Fire(TdEnemy target) { var s = Stats; var hitPoint = target.transform.position; if (s.splashRadius > 0f) { var r2 = s.splashRadius * s.splashRadius; // Copy first: damage can kill enemies, which removes them from the game's list. _inRange.Clear(); foreach (var e in _game.Enemies) if (e.Alive && (e.transform.position - hitPoint).sqrMagnitude <= r2) _inRange.Add(e); foreach (var e in _inRange) Hit(e, s); } else Hit(target, s); if (tracer != null) { tracer.SetPosition(0, muzzle != null ? muzzle.position : transform.position + Vector3.up); tracer.SetPosition(1, hitPoint + Vector3.up * 0.5f); tracer.enabled = true; _tracerOff = Time.time + 0.06f; } } static void Hit(TdEnemy e, in TowerDefinition.Level s) { if (s.slow > 0f) e.Slow(s.slow, s.slowSeconds); e.Damage(s.damage); } } ``` How it works: - **Every frame**, `FindTarget` builds a `TargetInfo` list of living enemies inside the range circle, using flat (XZ) distance, and asks `TargetPicker` for the best one. With 40 enemies and 20 towers that's 800 distance checks a frame, which is nothing. If you scale up to hundreds of each, check targets every 0.1 s instead, or bucket enemies by grid cell. - **The head turns instantly.** Towers that rotate slowly look nice but feel unfair at this scale. If you add a turn rate, fire only when facing within a few degrees. - **Cooldown:** after a shot the tower waits `1 / shotsPerSecond`. The cooldown keeps counting down while there's no target, so the first shot at a new arrival is immediate. - **Hits are instant.** Tower defense players judge placement, not ballistics, and a shell that misses a fast runner feels like a bug. A tracer sells the shot. - **Splash** hits every living enemy within the radius of the target, including the target. The list is copied first, because damage can kill enemies, and a killed enemy is removed from the game's list while you're looping over it. - **Upgrades** spend through the economy, add to `TotalSpent` for refunds, and resize the range disc if it's showing. ## Related - [[Game Programming Patterns (Review)]]: *Type Object* is the definitions; *Object Pool* explains why `Init` must reset everything. - [[Level Up! (Review)]]: counters and soft counters, which is the enemy-tower table in 3.1. - [[Object Pooling and Spawners]] for pooling in depth.