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

Scaling a shape

You will build: Draw a box (half-size 0.1 by 0.08) and stretch it to twice the width by dividing p.

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

Same idea for size. To make a shape bigger, make every pixel look at a position that is closer to the middle: divide by the scale.

Check: with p / 2.0 the pixel at x = 0.4 looks at 0.2, so a shape that ends at 0.2 now reaches all the way out to 0.4: twice as big. You can scale each direction separately: p / float2(2.0, 1.0) stretches only horizontally.

This lesson also introduces a ready-made helper, sdBox(p, halfSize). It gives the distance from p to a box: negative inside, 0 on the edge, positive outside. You don't have to understand its insides yet. Use the Toolbox button to add it.

To turn a distance into a picture: m = 1.0 - smoothstep(0.0, 0.01, d); is 1 inside, 0 outside, with a thin soft edge.

float2 p = (uv - 0.5) * float2(aspect, 1.0);
p = p / float2(2.0, 1.0);       // twice as wide, same height

The numbers you need

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

Box
sdBox(p, float2(0.1, 0.08))
Stretch
p = p / float2(2.0, 1.0)
Fill
float3(0.3, 0.8, 0.9)
Background
float3(0.08, 0.08, 0.12)
Edge
m = 1.0 - smoothstep(0.0, 0.01, d)

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

Go deeper

Part of the learning path: Shader art basics.