OpenSNES
Modern Open-Source SNES Development SDK
Loading...
Searching...
No Matches
Collision Detection Tutorial

This tutorial covers collision detection on the SNES, from basic bounding box checks to tile-based world collision used in platformers.

Why AABB?

The SNES has no hardware collision detection. All collision must be done in software by the CPU. Axis-aligned bounding box (AABB) testing is the standard approach because it requires only four comparisons per pair of objects – fast enough for the 65816 at 3.58 MHz.

The Rect Type

OpenSNES provides a Rect structure representing an axis-aligned bounding box:

#include <snes.h>
#include <snes/collision.h>
typedef struct {
s16 x; /* Left edge X coordinate */
s16 y; /* Top edge Y coordinate */
u16 width; /* Width in pixels */
u16 height; /* Height in pixels */
} Rect;
SNES Collision Detection.
signed short s16
16-bit signed integer (-32768 to 32767)
Definition types.h:50
unsigned short u16
16-bit unsigned integer (0 to 65535)
Definition types.h:53
OpenSNES common-case master header.
Axis-aligned bounding box (rectangle).
Definition collision.h:54

Initialize it with rectInit() or by direct assignment:

static Rect player_box
Kit's bounding box for AABB collision tests via collideRect().
Definition main.c:80
static s16 player_y
Kit's hitbox, top-left corner, Y.
Definition main.c:78
static s16 player_x
Kit's hitbox, top-left corner, in screen coordinates.
Definition main.c:76
void rectInit(Rect *r, s16 x, s16 y, u16 w, u16 h)
Initialize a rectangle.

When the player moves, rectSetPos(&player_box, player_x, player_y) moves the box without touching its size, and rectGetCenter(&box, &cx, &cy) gives its centre — the point to aim at, or to measure a distance from.

Sprite-to-Sprite Collision

Basic Overlap Test

Use collideRect() to test whether two rectangles overlap:

static void check_collisions(void) {
player_box.width = 16;
player_box.height = 16;
enemy_box.width = 16;
enemy_box.height = 16;
/* Collision detected */
player_hit();
}
}
static s16 enemy_y[4]
Drones' hitboxes, top-left corner Y.
Definition main.c:85
static void check_collisions(void)
Test Kit-vs-drone AABB overlap and update collision_flags.
Definition main.c:228
static Rect enemy_box[4]
Bounding boxes for each drone, rebuilt every frame for collideRect().
Definition main.c:87
static s16 enemy_x[4]
Drones' hitboxes, top-left corner X.
Definition main.c:83
u8 collideRect(const Rect *a, const Rect *b)
Check rectangle vs rectangle collision (AABB).

Testing Multiple Enemies

The collision_demo example checks Kit against four drones each frame using a bitmask to track which drones are currently overlapped:

#define NUM_ENEMIES 4
static void check_collisions(void) {
u8 i;
player_box.height = BOX_SIZE;
for (i = 0; i < NUM_ENEMIES; i++) {
enemy_box[i].width = BOX_SIZE;
enemy_box[i].height = BOX_SIZE;
collision_flags |= (1 << i);
}
}
}
static u8 collision_flags
Bitmask tracking which drones Kit is currently overlapping.
Definition main.c:95
#define NUM_ENEMIES
Definition main.c:57
#define BOX_SIZE
Definition main.c:56
static u8 i
Definition main.c:144
unsigned char u8
8-bit unsigned integer (0 to 255)
Definition types.h:47

Point-vs-Rectangle

Use collidePoint() when checking a single coordinate (bullet, cursor) against a target:

if (collidePoint(bullet_x, bullet_y, &target_box)) {
target_hit();
}
u8 collidePoint(s16 x, s16 y, const Rect *r)
Check point vs rectangle collision.

Sprite-to-Background Collision

Reading Tilemap Data

For platformers and top-down games, the world is made of tiles. A separate collision map (one byte per tile, 0 = empty, nonzero = solid) lets you check whether a pixel position is blocked:

#define MAP_WIDTH 16
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* Top wall */
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
/* ... */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* Bottom wall */
};
static const u8 collision_map[16 *14]
Tile-based collision map (16x14 = 224 bytes, 256x224 pixels).
Definition main.c:130
#define MAP_HEIGHT
Definition main.c:109
#define MAP_WIDTH
Definition main.c:108

Use collideTile() to look up the tile at a pixel position:

/* Standing on solid ground */
on_ground = 1;
}
u8 collideTile(s16 px, s16 py, const u8 *tilemap, u16 mapWidth)
Check collision with tile at pixel coordinates.

Checking All Four Corners

A single point check misses edges. The collision_demo example checks all four corners of Kit's bounding box to prevent clipping through walls. Its map has 16x16 cells, so it asks collideTileEx() with a cell size of 16 (CELL); the map covers the screen, so box coordinates are map coordinates:

static u8 check_wall_collision(s16 new_x, s16 new_y) {
/* Top-left */
if (collideTileEx(new_x, new_y, collision_map, MAP_WIDTH, CELL)) return 1;
/* Top-right */
if (collideTileEx(new_x + BOX_SIZE - 1, new_y, collision_map, MAP_WIDTH, CELL)) return 1;
/* Bottom-left */
if (collideTileEx(new_x, new_y + BOX_SIZE - 1, collision_map, MAP_WIDTH, CELL)) return 1;
/* Bottom-right */
if (collideTileEx(new_x + BOX_SIZE - 1, new_y + BOX_SIZE - 1, collision_map, MAP_WIDTH, CELL)) return 1;
return 0;
}
#define CELL
Definition main.c:110
static u8 check_wall_collision(s16 new_x, s16 new_y)
Test whether Kit's box at a position would overlap a solid cell.
Definition main.c:265
u8 collideTileEx(s16 px, s16 py, const u8 *tilemap, u16 mapWidth, u8 tileSize)
Check collision with tile using custom tile size.

You can also use collideRectTile() which does this internally:

Rect playerBox = { map_x, map_y, PLAYER_SIZE, PLAYER_SIZE };
/* Player hit a solid tile */
}
u8 collideRectTile(const Rect *r, const u8 *tilemap, u16 mapWidth)
Check collision between rectangle and tilemap.

Custom Tile Sizes

For maps with 16x16 tiles, use collideTileEx():

on_ground = 1;
}

Tile Properties from a Tilemap (Platformer Pattern)

The rooftop_run example uses 16-bit tile properties looked up from the visual tilemap, rather than a separate collision map. Each tile index maps to a property value (T_SOLID or T_EMPTY):

#define T_EMPTY 0x0000
#define T_SOLID 0xFF00
u16 tx, ty;
if (px < 0 || py < 0) return T_SOLID;
tx = (u16)px >> 3; /* Divide by 8 (tile width) */
ty = (u16)py >> 3;
if (tx >= map_width || ty >= map_height) return T_EMPTY;
return tile_props[map_row_ptrs[ty][tx] & 0x03FF];
}
static u8 px
Definition main.c:104
static u8 py
Definition main.c:104
static u16 map_height
Definition main.c:214
static u16 map_get_tile_prop(s16 px, s16 py)
Look up the collision property of the tile at pixel coordinates.
Definition main.c:310
static const u16 * map_row_ptrs[32]
Precomputed row pointers into map_data for fast tile lookup.
Definition main.c:225
static u16 map_width
Definition main.c:213
static const u16 * tile_props
Definition main.c:216
#define T_EMPTY
Empty tile (object will fall through).
Definition map.h:54
#define T_SOLID
Solid tile (blocks movement).
Definition map.h:57

This avoids storing a duplicate collision map – the visual tilemap doubles as the collision source.

Where the sprite is vs where it collides

In a top-down game the character occupies one tile, but its sprite is usually 16×16 — twice that tile. Where you draw those 16×16 pixels relative to the tile decides whether collision feels right, and it is the single most common source of "my collision is broken" reports that turn out to have nothing wrong with the collision code.

The naive version draws the sprite at the tile's corner:

oamSet(id, tile_x * 8 - cam_x, tile_y * 8 - cam_y, ...); /* wrong */
void oamSet(u16 id, u16 x, u16 y, u16 tile, u16 palette, u16 priority, u16 flags)
Set sprite properties.
u16 cam_y
Definition main.c:91
u16 cam_x
Probe oracles: the camera, the shards placed this frame, the resident in the front slot.
Definition main.c:90

The tile is 8×8 and the sprite is 16×16, so the visible body sits half a tile away from the thing that actually collides. Walking up to a wall, you stop with a visible gap on one side and clipping into it on the other, depending on the direction you approached from. Players report that as "collisions are random — sometimes too early, sometimes too late", which sends you reading collideTile(), where there is no bug.

The convention is to straddle the tile: feet on it, body overhanging upward.

u16 sx = (u16)(tile_x * 8 - cam_x - 4); /* centre the 16px body on an 8px tile */
u16 sy = (u16)(tile_y * 8 - cam_y - 8); /* stand the feet on the tile */
oamSet(id, sx, sy, ...);
u16 sy
Definition main.c:115
u16 sx
Definition main.c:114
┌────────┐
│ │ the sprite (16×16)
│ body │
├───┬────┤
│ │▓▓▓▓│ the tile it occupies (8×8),
└───┴────┘ and the only thing that collides

Now what you see is what collides, from every direction. examples/demos/rpg does this in draw_char() at twice the scale: its characters stand on a 16×16 metatile (two cells a side) and their 32×32 sprites are drawn 8 px left and 16 px up of it; a step asks collideTile() about the metatile's four cells.

Two consequences worth knowing:

  • The sprite overlaps the tile above it. That is intended — it is what makes a character look like it is standing in the scene rather than on top of it. It also means the tile above must be drawn before the sprite, i.e. the sprite needs a priority that puts it over the background layer.
  • Collision stays tile-exact. You are not colliding a 16×16 box against tiles; you are asking "is the tile I want to step into solid?". One collideTile() call per step, not four per frame.

Collision Response Patterns

Detecting a collision is only half the problem. What happens next matters more.

Stopping Movement (Slide Along Walls)

When the player tries to move diagonally into a wall, test each axis independently so they can slide along the wall instead of getting stuck:

new_x = player_x;
new_y = player_y;
if (pad & KEY_LEFT) new_x -= PLAYER_SPEED;
if (pad & KEY_RIGHT) new_x += PLAYER_SPEED;
if (pad & KEY_UP) new_y -= PLAYER_SPEED;
if (pad & KEY_DOWN) new_y += PLAYER_SPEED;
if (!check_wall_collision(new_x, new_y)) {
/* No collision -- accept full movement */
player_x = new_x;
player_y = new_y;
} else {
/* Try each axis separately */
player_x = new_x; /* Horizontal OK */
}
player_y = new_y; /* Vertical OK */
}
}
#define PLAYER_SPEED
Definition main.c:58
#define KEY_RIGHT
Definition input.h:81
#define KEY_DOWN
Definition input.h:79
#define KEY_LEFT
Definition input.h:80
#define KEY_UP
Definition input.h:78

Pushing Out of Overlap

Use collideRectEx() to get the overlap amount and push objects apart. This is useful for objects that can drift into each other (e.g., physics objects):

s16 dx, dy;
if (collideRectEx(&player, &wall, &dx, &dy)) {
/* dx, dy are the displacements that move `player` OUT of `wall`:
* ADD them. Resolve the axis of least penetration only — applying
* both pushes the object out diagonally. */
if ((dx < 0 ? -dx : dx) < (dy < 0 ? -dy : dy)) player_x += dx;
else player_y += dy;
}
u8 collideRectEx(const Rect *a, const Rect *b, s16 *overlapX, s16 *overlapY)
Check if two rectangles overlap and return overlap amount.

Subtracting them drives the player deeper into the wall; the library fixture pins the sign (dx = -6 for a player to the left of the wall).

Bouncing (Breakout Pattern)

The breakout example reverses velocity on collision with walls and paddle:

/* Wall bounce */
if (pos_x > 171) {
pos_x = 171;
}
/* Paddle bounce with angle control */
if (pos_y > 195 && pos_y < 203) {
if (pos_x >= px && pos_x <= px + 27) {
u8 zone = (pos_x - px) / 7;
switch (zone) {
case 0: vel_x = -2; vel_y = -1; break;
case 1: vel_x = -1; vel_y = -2; break;
case 2: vel_x = 1; vel_y = -2; break;
default: vel_x = 2; vel_y = -1; break;
}
}
}
static s16 vel_y
Definition main.c:174
static s16 pos_x
Definition main.c:175
static s16 pos_y
Definition main.c:176
static s16 vel_x
Ball X velocity (-2 to +2 pixels/frame).
Definition main.c:173

Snapping to Tile Grid (Platformer Landing)

When a falling character hits the ground, snap their Y position to the tile boundary to prevent sinking into the floor:

/* Ground check: test two points at the bottom edge */
prop = map_get_tile_prop(kit_x + 2, kit_y + 16);
if (prop == T_EMPTY)
prop = map_get_tile_prop(kit_x + 13, kit_y + 16);
if (prop != T_EMPTY) {
/* Snap to tile boundary */
kit_y = ((kit_y + 16) & 0xFFF8) - 16;
kit_yvel = 0;
on_ground = 1;
}
static s16 kit_y
Definition main.c:231
static s16 kit_x
Definition main.c:230
static s16 kit_yvel
Definition main.c:235

The mask 0xFFF8 rounds down to the nearest 8-pixel tile boundary. Subtracting the sprite height (16) places the sprite so its feet rest exactly on top of the solid tile.

Grid-Based Collision (Breakout Bricks)

The breakout example converts the ball's pixel position to a grid coordinate and checks a brick array directly:

/* Convert pixel to brick grid (16x8 pixel bricks) */
bx = (pos_x - 14) >> 4; /* Divide by 16 (brick width) */
by = (pos_y - 14) >> 3; /* Divide by 8 (brick height) */
if (bx < 10 && by >= 1 && by <= 10) {
u16 idx = bx + (by << 3) + (by << 1) - 10;
if (blocks[idx] != 8) {
/* Brick hit -- remove it and bounce */
}
}
static void remove_brick(void)
Remove a brick and update score.
Definition main.c:705
FAR u8 blocks[]
Mutable brick state array (100 entries, one per grid cell).
static u16 bx
Definition main.c:147
static u16 by
Definition main.c:147

Performance Tips

  1. Check collision only when objects are close. Skip collideRect() for enemies off screen.
  2. Use bitmasks for groups. Track collision state with bit flags (collision_flags |= (1 << i)) instead of boolean arrays.
  3. Separate axes. Test X and Y independently – this is cheaper than diagonal resolution and gives better sliding behavior.
  4. Power-of-2 tile sizes. Use 8 or 16 pixel tiles so division becomes a bit shift (>> 3 or >> 4).
  5. Avoid collideRect() in tight loops with many objects. For N-vs-N collision, consider spatial partitioning (grid cells) to reduce the number of pairs tested.

Complete Examples

  • examples/basics/collision_demo/ – AABB sprite collision with tile-based wall collision (16x16 cells, the map built from the collision array) and visual feedback
  • examples/games/breakout/ – Ball vs walls, ball vs paddle (angle control), ball vs brick grid
  • examples/games/rooftop_run/ – Platformer tile collision with gravity, ground snapping, and wall sliding

Next Steps