Recursive AI

Create a polygon collider from a sprite outline in C#

OnePhysics is a free, open-source physics library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Trace a sprite’s alpha mask into outlines, then split those outlines into convex polygon colliders. Transparent holes can stay empty.

OnePhysics is a standalone .NET physics engine; see the engine mapping guide when integrating with an existing game.

Terminal
dotnet add package RecursiveAI.OnePhysics
dotnet add package RecursiveAI.OnePhysics.Tools

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

For your own sprites, supply alpha bytes from your image decoder; the tracer doesn’t load PNG files.

C#
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics2D;
using RecursiveAI.OnePhysics.Tools;
// 3 by 3 mask; the center is transparent.
byte[] alpha = [255,255,255, 255,0,255,
    255,255,255];
var pieces = SpriteOutliner.ToConvexPieces(
    alpha, 3, 3, new() { Tolerance = 0 });
var world = new PhysicsWorld2D();
foreach (var piece in pieces)
    world.AddPolygon(piece, type: BodyType.Static);
Console.WriteLine(world.OverlapPointAny(new(1.5, 1.5)));

Prints:

Text
False

Unzip the example, then dotnet run.

The full program

The snippet at the top uses a three-by-three ring. The full program uses a five-by-five ring, reports its island and hole counts, and checks a solid border point and the transparent center. Each number in the inline mask is an alpha byte: 255 is opaque and 0 is transparent.

C#
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics2D;
using RecursiveAI.OnePhysics.Tools;
 
// A 5 by 5 opaque ring with a transparent 3 by 3 center.
byte[] alpha = [
    255,255,255,255,255,
    255,  0,  0,  0,255,
    255,  0,  0,  0,255,
    255,  0,  0,  0,255,
    255,255,255,255,255];
var islands = SpriteOutliner.Trace(alpha, 5, 5,
    new SpriteOutlineOptions { Tolerance = 0 });
var world = new PhysicsWorld2D();
int count = 0;
foreach (var island in islands)
    foreach (var piece in island.ToConvexPieces())
    {
        world.AddPolygon(piece, type: BodyType.Static);
        count++;
    }
Console.WriteLine($"Islands: {islands.Length}");
Console.WriteLine($"Holes: {islands[0].Holes.Length}");
Console.WriteLine($"Pieces: {count}");
Console.WriteLine($"Border hit: {world.OverlapPointAny(new Vector2D(2, 0.2))}");
Console.WriteLine($"Hole hit: {world.OverlapPointAny(new Vector2D(2, 2))}");
Text
Islands: 1
Holes: 1
Pieces: 11
Border hit: True
Hole hit: False

An invalid mask size or option throws GeometryToolException; a fully transparent mask returns no islands.

Variations

Scale pixels into world units. Append this to the full program to trace the same ring with each pixel measuring 0.1 world units.

C#
var smaller = SpriteOutliner.Trace(alpha, 5, 5,
    new SpriteOutlineOptions
    { PixelSize = 0.1f, Tolerance = 0 });
Console.WriteLine($"Islands: {smaller.Length}");
Console.WriteLine($"Holes: {smaller[0].Holes.Length}");
Text
Islands: 1
Holes: 1

The short answer

Give SpriteOutliner a row-major alpha-byte array, its width and its height. Trace the islands, decompose each island with ToConvexPieces, and create a static polygon for each returned piece. The combined geometry follows the sprite outline and leaves its transparent hole empty.

The input here is generated data rather than an image file. An image decoder in your application must supply the alpha channel; the tracing API does not read a PNG filename. The complete mask is visible above so the example needs no external asset.

How do you create a polygon collider from a sprite?

Start with alpha, not color. By default, samples with alpha at least 128 are solid. The outliner uses marching squares with interpolated threshold crossings, so contour points need not fall on integer pixel corners. This is a contour of the sampled mask, not a collection of one square collider per opaque pixel.

Trace returns islands with an outer loop and any enclosed holes. A concave island is not directly suitable for AddPolygon, which expects a convex piece. Call the island’s ToConvexPieces first; it handles its holes as part of polygon decomposition. The convenience SpriteOutliner.ToConvexPieces combines those stages, as the snippet at the top shows.

The full program creates static bodies so the pieces remain in place as one stationary collision outline. If you instead create independent dynamic polygons, they can move apart. For moving artwork, assemble the pieces into a single compound body rather than simulating each piece as an unrelated object.

Can a sprite collider preserve transparent holes?

Yes. The full example traces one island containing one hole. The border overlap succeeds and the center overlap fails. Testing both matters: creating a convex hull from only the outside boundary would fill the center even though the artwork is transparent there.

The default simplification tolerance is one pixel. The examples use zero tolerance to keep every traced contour vertex. MinArea can discard small islands and holes before simplification, so leave it at zero when tiny transparent openings are important. Inspect the resulting pieces with representative overlap queries rather than assuming every visual detail survives a chosen tolerance.

The tool specification states that ambiguous marching-squares cells keep diagonal solid samples apart. Diagonal pixel contact therefore does not automatically join two regions into one collider.

How do you align a sprite’s polygon collider?

The first alpha row is the image’s top row. By default the output uses y-up physics coordinates: points map to (x * PixelSize + Origin.X, (height - y) * PixelSize + Origin.Y). Match the same scale and origin in your renderer, including any sprite pivot offset. KeepImageRows leaves y growing downward instead.

PixelSize must be positive and finite. Origin places the lower-left image corner by default, or the upper-left corner when image rows are kept. The scale variation changes the traced coordinates; it does not automatically change your image rendering scale.

Masks must have exactly width times height bytes. Each dimension can be from 1 to 16384, with at most 2^26 pixels overall. Polygon decomposition accepts 3 to 16384 points across the outline and holes, and its default convex-piece vertex limit is eight. Large or very detailed masks may therefore need simplification before becoming collision geometry.

All onephysics recipes