AppStars

Spell Fighter: a neural network inside a game loop

In 2023 we put a neural network inside a Unity game loop: draw a glyph, and an on-device model scores it. The model was the easy part. Feeding it the right image was the work.

In 2023 we wanted to know whether a neural network could sit inside a real-time game loop and answer a simple question: what did the player just draw? The idea was a game we called Spell Fighter. You draw a symbol with the mouse, and the game recognises it and casts the matching spell. No server, no network call, just a model running on the player's own machine between frames.

It was an R&D prototype, not a shipped game. But it taught us something we have used on every on-device AI project since: the model is rarely the hard part. The hard part is everything between the real world and the model's input.

The problem: a model that expects one thing, and a player who gives you another

We started with a spike. Before training anything, we used a standard, publicly available MNIST handwritten-digit model in ONNX format, a small network of about 26 KB that classifies a 28×28 greyscale image into the digits 0 to 9. To run it inside Unity we used Barracuda, Unity's neural network inference library at the time. Both are third-party. Digits stood in for spell glyphs while we proved out the pipeline. Once it worked, we trained our own glyph model on our spell symbols and ran it the same way, on the device.

That split matters, because it shows where the engineering actually was. A model like this has a narrow contract. It was trained on digits that are:

  • white strokes on a black background
  • greyscale, one channel, 28×28 pixels
  • scaled to fit a smaller box and centred, with a margin of empty pixels around the edge

A player's mouse gives you none of that. You get a stream of screen coordinates, sampled once per frame, at whatever speed and size the player happens to draw. A quick flick across a 1080p window might produce a dozen points hundreds of pixels apart. Give a network that raw, and it will confidently tell you nonsense.

So our work was the glyph pipeline: turning a mouse stroke into an image the model would recognise, running inference without hurting the frame rate, and showing the result in a way we could reason about.

Architecture

The whole thing lives in one Unity component of about 300 lines, plus a few helpers.

mouse stroke (screen pixels)
  -> densify: interpolate between samples
  -> normalise: fit the stroke into a 24x24 box
  -> pad: centre it in a 28x28 greyscale texture
  -> tensor (1 channel) -> inference worker (GPU)
  -> 10 raw scores -> softmax -> best match + per-class weights on screen
  • Capture runs while the left mouse button is down. Releasing it ends the stroke and triggers recognition. The right button clears the canvas.
  • Preprocessing happens once per stroke, not once per frame, so the cost is paid only when the player finishes drawing.
  • Inference uses one worker created at start-up and reused for every stroke, and disposed when the component is destroyed.
  • Display shows the best match and all ten class weights, so we could see how sure the model was, not only what it picked.

The engineering

1. Densify the stroke so fast drawing has no gaps

Mouse positions arrive once per frame. Draw quickly and consecutive samples are far apart, so the stroke would arrive at the model as a scatter of dots. We fill the gaps by stepping along the line between each pair of samples, one point per pixel of the longer axis:

private void AddLine(Vector2 start, Vector2 end)
{
    float deltaX = end.x - start.x;
    float deltaY = end.y - start.y;

    for (float i = 0; i <= 1; i += (float) 1 / Math.Max(Math.Abs(deltaX), Math.Abs(deltaY)))
    {
        float x = start.x + i * deltaX;
        float y = start.y + i * deltaY;
        AddPosition(new Vector2(x, y));
    }
}

It is the same idea as a line-drawing routine in a software renderer. The result is a continuous stroke no matter how fast the player draws.

2. Match the training data, not the screen

Next we find the stroke's bounding box and scale every point into a 24×24 area. Then we offset it by two pixels into the 28×28 input texture, so there is a margin on every side, the way the training digits were framed. Each point is drawn as a 2×2 white block on black, which gives a stroke weight closer to a pen than to a single-pixel line.

This is the step that made recognition work. Before it, the model was effectively being shown images from a different world. After it, a drawn digit looked like the digits the model had learned from.

There is a trade-off worth naming. Our prototype normalised the x and y axes separately, so every stroke was stretched to fill the square. That is fine for most shapes, but it distorts tall, thin ones such as a "1", and a perfectly vertical stroke has no width to divide by. A production version would scale by the longer side to keep the aspect ratio, and guard the degenerate case. Prototypes are for finding exactly this kind of thing.

3. Inference that stays out of the frame budget

The inference itself is short. We build a one-channel tensor straight from the texture, execute the model, read the ten outputs, and dispose of the input tensor so nothing leaks between strokes:

var inputX = new Tensor(_textureModelInput, channelCount);
Tensor outputY = _engine.Execute(inputX).PeekOutput();
inputX.Dispose();

var scores = Enumerable.Range(0, 10).
             Select(i => outputY[0, 0, 0, i]).SoftMax().ToArray();

The worker is created once with WorkerFactory.CreateWorker(model, Device.GPU) and reused. Every run logs its own inference time, because the only honest answer to "is it fast enough?" is a measurement on the target machine.

For a model this small, the GPU is not automatically the right choice. Moving a tiny input to the GPU and reading the result back can cost more than the maths itself, so the CPU path is worth measuring too. That is the kind of decision we now make per device, from numbers, rather than by default.

4. Show the confidence, not just the answer

The model returns raw scores. We pass them through a softmax, written as a small extension method, so the ten values become weights that add up to one:

public static IEnumerable<float> SoftMax(this IEnumerable<float> source)
{
    var exp = source.Select(x => Mathf.Exp(x)).ToArray();
    var sum = exp.Sum();
    return exp.Select(x => x / sum);
}

Seeing all ten weights on screen changed how we tested. A stroke that wins at 0.95 is a different situation from one that wins at 0.31 with three close rivals. A game built on this needs a threshold: below a certain confidence, the spell fizzles instead of firing the wrong one. That is a game design rule, but it is also the same rule we apply to any model output a person acts on.

Where AI fits

Spell Fighter is the AI. It is a classifier running locally, in the loop, with no cloud involved. It sits in a line of gesture work that goes back a long way: a mouse-gesture recogniser in 2002, and a Kinect gesture engine in 2011 where you waved patterns in the air to cast spells. Those earlier versions matched gestures with hand-written rules. This one handed the matching to a learned model, and moved our effort to the input side.

You can read about the Kinect engine in Kinect gestures and a vision lap timer, and about where this thread led in 25 years of putting AI to work.

What it taught us

  • Treat the model as a component with a contract. Write down what it expects (size, channels, scale, framing, value range) and make preprocessing the code that honours that contract. Most "the model is bad" problems are really "the input is wrong" problems.
  • Spike with an off-the-shelf model first. Using a standard model let us prove the capture, preprocessing and runtime before spending anything on training. Only once the pipeline was known to work did we train our own model on the real spell glyphs.
  • Measure on the device. Log inference time every run. Decide CPU or GPU from data.
  • Surface confidence. If people or game logic act on a prediction, they need to know how sure it is.

Why it still matters

The same pattern now runs on phones, tablets and smart glasses: capture something from the real world, shape it into exactly what a model expects, run it on the device, and act on the result with an eye on confidence. It is how we approach on-device and edge AI for clients, where data shouldn't leave the device and the network can't be relied on. If that's your problem, our wearables and edge AI page shows how we work, and Gemma on the glasses shows where the idea went next.

Bring us the hard problem.

A 45-minute discovery call with the engineer who'll build it.