2D toolkit · lesson 6 of 8 · Intermediate · about 5 min

Rotation & matrices

You will build: Spin the box: rotate p by an angle equal to time (in radians) before computing the distance.

The picture produced by the shader in the lesson "Rotation & matrices"
The target picture. In the lesson you write the shader that draws it, and a match bar shows how close you are.

You now know how to move, scale and turn a shape by changing the pixel's position first. This lesson adds two things: spinning over time and the matrix shorthand.

Last lesson you wrote the turn as two lines with c and s. A matrix is just a tidy way to write those same numbers:

float2 p = (uv - 0.5) * float2(aspect, 1.0);
float a = time;                       // the angle grows by 1 radian every second
float2x2 R = float2x2(cos(a), -sin(a),
                      sin(a),  cos(a));
p = mul(R, p);                        // apply it to the pixel's position

mul(R, p) does exactly float2(c*p.x - s*p.y, s*p.x + c*p.y). Nothing new is happening: the matrix is just a table of those four numbers, and mul does the “multiply and add” for you.

Spinning is then easy: make the angle grow with time.

The box comes from the helper sdBox (Toolbox). Your job is only the order: turn p first, measure the box after.

The numbers you need

Everything the picture depends on is given, so the challenge is the code, not guessing.

Angle
time
Box half-size
float2(0.18, 0.1)
Fill
float3(0.3, 0.8, 0.9)
Background
float3(0.07, 0.07, 0.1)

Try it in your own language

The lesson is written once and shown in every language. Pick yours: Unity (Built-in), Unity (URP), Unreal, Shadertoy / WebGL, OpenGL (LWJGL, raylib), three.js, GameMaker, LÖVE (Lua), Godot, Apple (iOS, macOS), WebGPU / Bevy.

Start coding