# 2. Space Invaders Player Cannon and Bullets
Part of [[Space Invaders]]. Previous: [[1. Space Invaders Project Setup and Playfield]]. Next: [[3. Space Invaders Invader Formation]].
## 2.1 One interface for everything that can be shot
Invaders, bunker cells, the UFO and the cannon all react to bullets differently. Instead of tags and `if` chains, each one implements `IShootable.TakeHit(bullet)` and returns **true if it consumed the bullet**. An invader ignores invader shots (returns false), so those pass through the rack.
## 2.2 The bullet
The bullet is a **kinematic** `Rigidbody2D` with a trigger collider, moved by velocity. Physics 2D only reports contacts between a kinematic body and static or kinematic colliders when **Use Full Kinematic Contacts** is on. The invaders and bunkers here have no Rigidbody2D (they're static colliders), so the bullet turns that option on in `Awake`.
```csharp
using System;
using UnityEngine;
/// <summary>
/// A straight-moving kinematic projectile. Used by the player (up) and invaders (down).
/// Returned to its pool on any trigger hit or when it leaves the playfield.
/// Needs: Rigidbody2D (Kinematic), a trigger Collider2D, and the right physics layer.
/// </summary>
[RequireComponent(typeof(Rigidbody2D))]
public sealed class Bullet : MonoBehaviour
{
[SerializeField] float speed = 12f;
[SerializeField] float maxAbsY = 6f;
Rigidbody2D _rb;
Action<Bullet> _release;
bool _live;
public bool FromPlayer { get; private set; }
void Awake()
{
_rb = GetComponent<Rigidbody2D>();
_rb.bodyType = RigidbodyType2D.Kinematic;
// Kinematic bodies only report triggers against non-static colliders unless full contacts are on;
// invaders and bunkers are kinematic or static, so turn it on.
_rb.useFullKinematicContacts = true;
}
public void Launch(Vector2 position, float direction, bool fromPlayer, Action<Bullet> release)
{
transform.position = position;
FromPlayer = fromPlayer;
_release = release;
_live = true;
gameObject.SetActive(true);
_rb.position = position;
_rb.linearVelocity = new Vector2(0f, direction * speed);
}
void FixedUpdate()
{
if (_live && Mathf.Abs(_rb.position.y) > maxAbsY)
Despawn();
}
void OnTriggerEnter2D(Collider2D other)
{
if (!_live)
return;
if (other.TryGetComponent<IShootable>(out var target) && target.TakeHit(this))
Despawn();
}
public void Despawn()
{
if (!_live)
return;
_live = false;
_rb.linearVelocity = Vector2.zero;
if (_release != null)
_release(this);
else
gameObject.SetActive(false);
}
}
/// <summary>Anything a bullet can hit. Return true if the bullet is consumed.</summary>
public interface IShootable
{
bool TakeHit(Bullet bullet);
}
```
> [!note] Not verified in the Editor
> The trigger behaviour between a kinematic body with full kinematic contacts and static trigger colliders comes from the Rigidbody2D documentation's description of the option. It wasn't play-tested here. If shots pass through invaders, add a Kinematic `Rigidbody2D` to each invader as well.
Bullet prefab: a 1×4 px sprite, a `BoxCollider2D` with **Is Trigger** on, a `Rigidbody2D` (the script sets Kinematic), the `Bullet` component, and the layer `PlayerShot`. Make a second prefab on `InvaderShot` with a zig-zag sprite for invader fire.
## 2.3 The cannon
`PlayerCannon` builds its input actions in code, which keeps the tutorial asset-free:
- **Move**: an A/D composite, a ←/→ composite, and the gamepad left stick X.
- **Fire**: Space and the gamepad South button.
It moves within `minX`/`maxX`, and it **only fires when no player bullet is alive** (`_active == null`). The pool's release callback clears `_active`. `ShotsFired` is counted for the UFO score table (part 4). When an invader shot hits it, the cannon is "dead" for `respawnSeconds`: it ignores input and further shots, and raises `Hit`.
```csharp
using System;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Pool;
/// <summary>
/// The laser base: moves left/right inside the bounds and fires one bullet at a time
/// (the arcade rule that makes every shot matter). Input actions are built in code so the
/// tutorial needs no .inputactions asset; swap for an asset later (see Input System notes).
/// </summary>
public sealed class PlayerCannon : MonoBehaviour, IShootable
{
[SerializeField] float speed = 4f;
[SerializeField] float minX = -3.2f;
[SerializeField] float maxX = 3.2f;
[SerializeField] Bullet bulletPrefab;
[SerializeField] Vector2 muzzleOffset = new Vector2(0f, 0.3f);
[SerializeField] float respawnSeconds = 1.5f;
InputAction _move;
InputAction _fire;
ObjectPool<Bullet> _pool;
Bullet _active;
float _deadUntil;
public int ShotsFired { get; private set; }
public bool IsDead => Time.time < _deadUntil;
public event Action Hit;
void Awake()
{
_move = new InputAction("Move", InputActionType.Value);
_move.AddCompositeBinding("1DAxis").With("Negative", "<Keyboard>/a").With("Positive", "<Keyboard>/d");
_move.AddCompositeBinding("1DAxis").With("Negative", "<Keyboard>/leftArrow").With("Positive", "<Keyboard>/rightArrow");
_move.AddBinding("<Gamepad>/leftStick/x");
_fire = new InputAction("Fire", InputActionType.Button);
_fire.AddBinding("<Keyboard>/space");
_fire.AddBinding("<Gamepad>/buttonSouth");
_pool = new ObjectPool<Bullet>(
() => Instantiate(bulletPrefab),
b => { },
b => b.gameObject.SetActive(false),
b => Destroy(b.gameObject),
collectionCheck: true, defaultCapacity: 1, maxSize: 2);
}
void OnEnable() { _move.Enable(); _fire.Enable(); }
void OnDisable() { _move.Disable(); _fire.Disable(); }
void OnDestroy() { _move.Dispose(); _fire.Dispose(); }
void Update()
{
if (IsDead)
return;
var x = transform.position.x + _move.ReadValue<float>() * speed * Time.deltaTime;
transform.position = new Vector3(Mathf.Clamp(x, minX, maxX), transform.position.y, 0f);
if (_fire.WasPressedThisFrame() && _active == null)
{
_active = _pool.Get();
ShotsFired++;
_active.Launch((Vector2)transform.position + muzzleOffset, +1f, true, Release);
}
}
void Release(Bullet b)
{
if (_active == b)
_active = null;
_pool.Release(b);
}
public bool TakeHit(Bullet bullet)
{
if (bullet.FromPlayer || IsDead)
return false;
_deadUntil = Time.time + respawnSeconds;
Hit?.Invoke();
return true;
}
}
```
Prefab: cannon sprite, `BoxCollider2D` (**Is Trigger** on), layer `Player`, `PlayerCannon` with the PlayerShot bullet prefab. Place it at (0, −3.6).
> [!tip] Switching to an actions asset later
> Code-built actions are fine for a jam, but players can't rebind them. When you want rebinding and control schemes, move these bindings to an `.inputactions` asset and read them through a generated class or `PlayerInput` ([[Input System]]). The rest of the code doesn't change.
## 2.4 Why a pool for one bullet?
With the one-shot rule, there's only ever one player bullet. The pool is mostly about *habit and invader fire* (part 4 reuses the same `Bullet` with its own pool), and about never calling `Instantiate` in the middle of play. `maxSize: 2` keeps it honest. It's the *Object Pool* chapter of [[Game Programming Patterns (Review)]], and [[Object Pooling and Spawners]] covers `ObjectPool<T>` in depth.
## Exercises
1. Add a 0.1 s fire cooldown *in addition to* the one-shot rule, and feel the difference when you shoot an invader point-blank.
2. Add a "rapid fire" power-up that allows two bullets for 10 s ([[Power-Ups, Pickups and Unlockables]]). Which one line changes?