Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: Build a Top-Down Shooter in Unity

Build a top-down shooter in Unity - twin-stick movement, mouse aiming, pooled bullets, enemy waves, health and score UI, with runnable aiming, fire-rate and wave stand-ins.

A top-down shooter is a perfect second project: the camera looks down on the arena, the player moves in all directions, aims at the mouse (or a gamepad stick) and shoots waves of enemies. You will practice vector math, input, object pooling, spawning, enemy AI and UI.

Unity is not available here, so the project steps and MonoBehaviour scripts are read-only. The math at the heart of the game (aim angles, fire rate, spread, wave scaling) runs as plain C# stand-ins.

Setup

Use the Universal 2D template, or 3D with an orthographic camera looking down. This guide uses 2D physics. Create layers Player, Enemy, PlayerBullet and EnemyBullet; in the collision matrix let PlayerBullet collide only with Enemy and walls. Add a background, a few wall tiles with colliders and a Cinemachine camera following the player with light damping.

Player movement and aiming

The player is a sprite with a dynamic Rigidbody2D (gravity scale 0, drag/linear damping around 8 for snappy stops). Movement reads a Vector2 from the Input System (WASD or left stick) and aim comes from the mouse position converted to world space, or from the right stick.

C#
using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerShooter : MonoBehaviour
{
    [SerializeField] float moveSpeed = 7f;
    [SerializeField] InputActionReference move, fire;
    [SerializeField] Transform muzzle;
    [SerializeField] BulletPool bullets;
    [SerializeField] float fireInterval = 0.15f;
    [SerializeField] float spreadDegrees = 3f;

    Rigidbody2D rb;
    Camera cam;
    float nextShot;

    void Awake() { rb = GetComponent<Rigidbody2D>(); cam = Camera.main; }
    void OnEnable()  { move.action.Enable(); fire.action.Enable(); }
    void OnDisable() { move.action.Disable(); fire.action.Disable(); }

    void FixedUpdate() => rb.linearVelocity = move.action.ReadValue<Vector2>() * moveSpeed;

    void Update()
    {
        Vector2 mouse = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        Vector2 aim = mouse - (Vector2)transform.position;
        float angle = Mathf.Atan2(aim.y, aim.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle - 90f);   // sprite faces up

        if (fire.action.IsPressed() && Time.time >= nextShot)
        {
            nextShot = Time.time + fireInterval;
            float jitter = Random.Range(-spreadDegrees, spreadDegrees);
            Vector2 dir = Quaternion.Euler(0, 0, angle + jitter) * Vector2.right;
            bullets.Fire(muzzle.position, dir);
        }
    }
}

Mathf.Atan2 gives the angle of the aim vector, and the spread adds a random offset. Here is the same math as runnable code.

C# Stand-in: aim angle, spread and fire rate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Bullets from a pool

Bullets are created constantly, so use the pool from Object pooling and memory. A bullet moves along its direction in FixedUpdate (or uses rb.linearVelocity), damages what it hits through an IDamageable interface and returns to the pool after a lifetime or a hit.

C#
using UnityEngine;

public interface IDamageable { void TakeDamage(int amount); }

public class Bullet : MonoBehaviour
{
    [SerializeField] float speed = 18f;
    [SerializeField] int damage = 1;
    [SerializeField] float lifetime = 1.5f;
    BulletPool owner;
    Vector2 direction;
    float dieAt;

    public void Launch(BulletPool pool, Vector2 pos, Vector2 dir)
    {
        owner = pool; direction = dir.normalized;
        transform.SetPositionAndRotation(pos, Quaternion.FromToRotation(Vector2.right, direction));
        dieAt = Time.time + lifetime;
    }

    void Update()
    {
        transform.position += (Vector3)(direction * (speed * Time.deltaTime));
        if (Time.time >= dieAt) owner.Release(this);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.TryGetComponent(out IDamageable target)) target.TakeDamage(damage);
        owner.Release(this);
    }
}

Fast bullets can pass through thin walls between frames ("tunneling"). Use CollisionDetectionMode2D.Continuous on a Rigidbody2D bullet or a short raycast from the previous to the new position.

Enemies and health

A simple chaser moves toward the player and deals contact damage on a cooldown. Give every damageable thing a shared Health component:

C#
using UnityEngine;
using UnityEngine.Events;

public class Health : MonoBehaviour, IDamageable
{
    [SerializeField] int max = 3;
    public UnityEvent<int, int> onChanged;     // current, max
    public UnityEvent onDied;
    int current;

    void OnEnable() { current = max; onChanged.Invoke(current, max); }

    public void TakeDamage(int amount)
    {
        current = Mathf.Max(0, current - amount);
        onChanged.Invoke(current, max);
        if (current == 0) onDied.Invoke();
    }
}

public class Chaser : MonoBehaviour
{
    [SerializeField] float speed = 3f;
    Transform target;
    void Start() => target = GameObject.FindWithTag("Player").transform;
    void Update() => transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}

Hook onChanged of the player's Health to a UI slider and onDied to a game-over panel (UI events). Enemies on death spawn a particle burst, add score and return to their pool.

Waves

A wave spawner is a coroutine: wait, spawn N enemies at random points around the screen edge, wait until they are all dead, then start the next wave with more or tougher enemies. A formula keeps difficulty rising smoothly rather than jumping.

C# Stand-in: wave scaling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C#
using System.Collections;
using UnityEngine;

public class WaveSpawner : MonoBehaviour
{
    [SerializeField] EnemyPool enemies;
    [SerializeField] float arenaRadius = 12f;
    int alive;

    void Start() => StartCoroutine(Run());

    IEnumerator Run()
    {
        for (int wave = 1; ; wave++)
        {
            int count = Mathf.RoundToInt(4 + wave * 1.5f + Mathf.Pow(wave, 1.2f));
            alive = count;
            for (int i = 0; i < count; i++)
            {
                Vector2 pos = Random.insideUnitCircle.normalized * arenaRadius;
                enemies.Spawn(pos, () => alive--);
                yield return new WaitForSeconds(0.4f);
            }
            yield return new WaitUntil(() => alive <= 0);
            yield return new WaitForSeconds(2f);      // breather between waves
        }
    }
}

Polish and extensions

  • Feel: muzzle flash, screen shake (Cinemachine Impulse), hit sparks, a short white flash on damaged enemies, knockback, sounds with pitch variation.
  • Weapons: shotgun (several bullets with spread), laser (raycast), grenade (area damage via Physics2D.OverlapCircleAll), and power-ups dropped with a probability.
  • Systems: a ScriptableObject WeaponData so a designer can add weapons without code; high-score saving; a main menu and settings.
  • Performance: pool bullets, enemies and particles; keep colliders simple; profile with the tools from Profiler and optimization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function converts an aim vector to an angle?

    Atan2 returns the angle of the vector in radians; multiply by Rad2Deg for degrees.
  2. 2. Why are bullets pooled?

    Reusing objects avoids allocations and GC hitches.
  3. 3. What is bullet tunneling?

    Continuous collision detection or raycasts prevent it.
  4. 4. Why use an IDamageable interface?

    Interfaces decouple the damage dealer from the receiver.

Summary

  • Twin-stick control = Input System movement plus mouse or stick aiming with Atan2.
  • A fire-rate cooldown, small random spread and pooled bullets give a responsive shooting feel.
  • An IDamageable interface and a shared Health component keep damage code simple.
  • Wave spawners with smooth difficulty formulas and polish effects complete the game.

Next: Project: An Endless Runner