Math & trig

Free functions on Sketch, mirroring Processing's globals. All angles are radians (RotateDegrees() is the one degrees-based helper).

On this page · 1 entry
constantvalue
PI / TWO_PI / TAUπ, 2π, 2π (alias)
HALF_PI / QUARTER_PIπ/2, π/4
functiondoes
Sin / Cos / Tan / Asin / Acos / Atan / Atan2Standard trig
Degrees(rad) / Radians(deg)Angle unit conversion
Constrain(v, min, max)Clamps a float or int
Dist(...)Distance between points
Mag(x, y) / Mag(x, y, z)Distance from the origin — the free-function form of PVector.Mag()
Lerp(start, stop, amt)Linear interpolation
Norm(value, start, stop)Normalizes into [0, 1]
Map(value, s1, e1, s2, e2)Remaps a value
Sq / Sqrt / Abs / Ceil / Floor / Round / Pow / Log / ExpScalar math
Max(...) / Min(...)Two-argument or params-array

Runnable example

A complete sketch using this section. Test in Dana opens it in the IDE, or paste it into a new tab and press Run.

C#
// Map, Constrain, Lerp, Dist and trig: a ball that eases toward the mouse.
public class Easing : Sketch
{
    float x = 300, y = 200;

    public override void Setup() => Size(600, 400);

    public override void Draw()
    {
        Background(240);
        x = Lerp(x, MouseX, 0.08f);
        y = Lerp(y, MouseY, 0.08f);

        float d = Dist(x, y, MouseX, MouseY);
        float size = Constrain(Map(d, 0, 200, 20, 80), 20, 80);
        Fill(60, 120, 200); NoStroke();
        Circle(x, y, size);

        // Atan2 gives the angle toward the mouse.
        float a = Atan2(MouseY - y, MouseX - x);
        Stroke(200, 60, 60); StrokeWeight(3);
        Line(x, y, x + Cos(a) * 60, y + Sin(a) * 60);

        Fill(30);
        Text($"distance {d:0} · angle {Degrees(a):0}°", 10, 20);
    }
}