3D with raymarching · lesson 3 of 7 · Intermediate · about 5 min

3D, step 2: is a point inside the sphere?

You will build: Colour pixels orange when the point 3 units along their ray is inside the sphere (radius 1 at the origin), otherwise dark.

The picture produced by the shader in the lesson "3D, step 2: is a point inside the sphere?"
The target picture. In the lesson you write the shader that draws it, and a match bar shows how close you are.

A point along the ray is ro + rd * t, where t is "how far along". t = 0 is the camera, t = 3 is three units out.

A sphere of radius 1 at the origin is simple to test: a point is inside it when its distance from the origin is less than 1: length(pos) < 1.0. (It is the circle test from the 2D lessons, with one more dimension.)

Test just one point per pixel, 3 units along its ray. The camera is at z = -3, so that point is about at z = 0, the middle of the sphere. Pixels whose point is inside the sphere get the sphere colour:

float2 p = (uv - 0.5) * float2(aspect, 1.0) * 2.0;
float3 ro = float3(0.0, 0.0, -3.0);
float3 rd = normalize(float3(p, 1.5));
float3 pos = ro + rd * 3.0;                // a point 3 units along the ray
float inside = step(length(pos), 1.0);     // 1 if it is inside the sphere

You will see a disc. Why only a disc and not a ball? We only tested one point per ray, so we found the sphere's silhouette, not its surface. Next step fixes that by walking along the ray.

The numbers you need

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

Colors
inside float3(0.9, 0.45, 0.3), outside float3(0.05, 0.06, 0.1)
Point
pos = ro + rd * 3.0
Test
step(length(pos), 1.0)

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