0Pricing
Learn Rust Coding · Lesson

Collisions and Game State

Add rules and win conditions.

AABB Collision Basics

The simplest collision test is axis-aligned bounding box (AABB) overlap. Two rectangles collide when they overlap on both the x and y axes.

For sprites this is fast and good enough for many 2D games before reaching for a full physics engine.

fn overlaps(a_pos: Vec2, a_size: Vec2, b_pos: Vec2, b_size: Vec2) -> bool {
    (a_pos.x - b_pos.x).abs() < (a_size.x + b_size.x) * 0.5
        && (a_pos.y - b_pos.y).abs() < (a_size.y + b_size.y) * 0.5
}

A Collider Component

Attach a Collider component holding each entity's half-extents or full size. Systems then read transform plus collider to test overlaps.

Keeping size in its own component lets different entities share the same collision system.

#[derive(Component)]
struct Collider {
    size: Vec2,
}

All lessons in this course

  1. The ECS Mindset
  2. Spawning and Moving Entities
  3. Handling Input and Time
  4. Collisions and Game State
← Back to Learn Rust Coding