agentleFS
nick-vasnick-vas/hyperdot/.agents/skills/math/SKILL.md

math

Skill1 starsChanged yesterdayApache-2.0View on GitHub

Use when Godot game code needs rotations, angles between directions, reflections and bounces, jumps set by height and distance, easing curves or smoothing that holds at any frame rate, or when a textbook formula and the engine disagree.

4 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Prefer Basis and Quaternion over hand-built 3 x 3 matrices.

    line 64
  2. Very specific:

    Never lerp a Basis or matrix component by component: halfway through a 162 degree turn the object is squashed to 0.16 of its width …

    line 69
  3. Very specific:

    Keep time as the sum of delta (game time), so motion stays deterministic for tests and bots (automation-hooks).

    line 85
  4. Very specific:

    Never pick gravity first and tune a jump speed against it: retuning "floaty" then breaks every gap measured in the levels.

    line 125

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Game math in Godot 4

Adapted from Denny Burzynski, Mathematics for Game Developers (LibreTexts, CC BY 4.0, math.libretexts.org): its chapters on vectors, matrices and trigonometry, mapped to Godot's API and conventions. The book's worked examples were rechecked in Godot 4.7.2 and match; its exercise answer key has errors (see "Test it").

First: Godot's conventions differ from the textbook's

TextbookGodot 4
2D axesorigin bottom-left, y uporigin top-left, y down (Vector2.Down is (0, 1))
Positive angle in 2Dcounterclockwiseclockwise on screen: Vector2.Right.Rotated(Mathf.Pi / 2) is (0, 1), pointing down
Unitsdegreesradians; convert with Mathf.DegToRad / Mathf.RadToDeg
3Dright-handedright-handed, y up, forward is -Z (Vector3.Forward is (0, 0, -1))
Positive 3D rotationcounterclockwise, "looking at an axis straight on toward the origin"the same, so a positive turn about Vector3.Up turns a -Z-facing object to its left: Vector3.Forward.Rotated(Vector3.Up, Mathf.Pi / 2) and RotateY(Mathf.Pi / 2) give (-1, 0, 0); "turn right" is a negative angle
Rotation matrixthe 2 x 2 rows [cos -sin; sin cos]Transform2D and Basis store columns: basis.X, .Y, .Z are the rotated axes

So a direction the book writes as (cos 30, sin 30) (up and to the right) points down and to the right on a Godot screen; mirror the y component, or the angle, when porting a y-up formula. The yaw sign, the cross product as area and how System.Numerics differs (no Forward; A * B applies A first) are pinned on Godot's types in ${CLAUDE_PLUGIN_ROOT}/examples/csharp/game/test/gdunit4/MathConventionsTest.cs.

Vectors (chapters 2 and 3)

IdeaGodot (C#)Game use
Add, subtract, scalea + b, a - b, a * 3move: Position += Velocity * (float)delta
Magnitudev.Length(); v.LengthSquared() when only comparingspeed, range checks without a square root
Direction (angle)v.Angle(), Vector2.FromAngle(a)aim, facing
Unit vectorv.Normalized() (zero stays zero)direction without speed
Dot producta.Dot(b)positive: in front; zero: perpendicular; negative: behind (field of view checks)
Angle betweena.AngleTo(b) (signed in 2D), Mathf.Acos(a.Normalized().Dot(b.Normalized()))turn toward a target
Parallel or perpendiculara.Cross(b) == 0 / a.Dot(b) == 0 (compare with a tolerance: Mathf.IsZeroApprox)
Projectionu.Project(v)the part of a move along a wall; the book's (4, 3) onto (2, 8) = (16/17, 64/17)
Cross product (3D)a.Cross(b)a surface normal from two edges; Vector3.Right.Cross(Vector3.Up) is +Z
Cross product (2D)a.Cross(b) returns a numberits sign says which side: positive means b is clockwise from a on screen
Cross product as areaa.Cross(b).Length() (3D), Mathf.Abs(a.Cross(b)) (2D)the parallelogram on a and b, half for the triangle ("produces the area of a parallelogram"; the book's ⟨1, −2, −4⟩ and ⟨4, 3, −5⟩: 26.94 and 13.47); near 0 means a degenerate triangle

The book's ball and wall (2.6). The ball's distance from a wall is the length of the part of its position not along the wall: (p - p.Project(wallDir)).Length(). For movement, Godot does the decomposition for you:

You wantUseVelocity (3, 4) hitting a floor whose normal is Vector2.Up
Slide along the surfacev.Slide(normal)(3, 0)
Bounce off itv.Bounce(normal)(3, -4)
Mirror across the normal's linev.Reflect(normal)(-3, 4): not a bounce, a common bug

CharacterBody2D.MoveAndSlide() slides for you; GetLastSlideCollision().GetNormal() gives the normal to bounce from.

Matrices and rotation (chapter 4)

  • Rotate a vector: v.Rotated(angle) (2D), v.Rotated(axis, angle) (3D, axis normalised).
  • A node's transform is a matrix with an origin: Transform2D(rotation, position), Transform3D(basis, origin). Apply it with transform * point; go from world to local with transform.AffineInverse() * point (or ToLocal / ToGlobal).
  • Order matters, as in the book's matrix products: a * b applies b first.
  • Angle of rotation between two vectors (4.5): from.AngleTo(to) in 2D; in 3D, new Quaternion(from.Normalized(), to.Normalized()) gives the rotation itself.
  • Prefer Basis and Quaternion over hand-built 3 x 3 matrices; interpolate rotations with Quaternion.Slerp, never by interpolating angles past 180 degrees (Mathf.LerpAngle wraps correctly in 2D).
  • Interpolation traps, from "A Visual Guide to Quaternions and Dual Quaternions" (GDC), checked in Godot 4.7.2:
    • q and -q are the same orientation, one the long way round. Slerp flips the sign itself (10 to -(80) degrees gives 45 halfway); Slerpni and hand-written lerps do not (135): check a.Dot(b) < 0 and negate first.
    • Never lerp a Basis or matrix component by component: halfway through a 162 degree turn the object is squashed to 0.16 of its width (determinant 0.02). Use Basis.Slerp or Transform3D.InterpolateWith, which keep scale 1.
    • Normalised lerp is not constant-speed (a quarter of a 160 degree turn gives 34.5 degrees; Slerp 40).
    • Normalise before rotating a vector: in C# a debug build throws "Quaternion is not normalized."; a release build silently stretches the vector. Build rotations with new Quaternion(axis, angle) (it halves the angle for you) or Basis.FromEuler(angles, EulerOrder.Yxz) with the order named, never with sin and cos by hand.
    • Skinned characters whose forearms twist flat (the candy wrapper) need dual-quaternion or "preserve volume" skinning in the 3D tool; whether Godot's Skeleton3D offers it was not checked.

Trigonometry (chapter 5)

  • On the unit circle, cos gives the horizontal and sin the vertical offset: circle motion is center + new Vector2(Mathf.Cos(t), Mathf.Sin(t)) * radius (clockwise on screen, since y is down).
  • The book's y = A sin(B x) has amplitude A and period 360/B degrees. In game time, with a period of T seconds: offset = A * Mathf.Sin(Mathf.Tau * time / T). A bobbing pickup: A = 4 px, T = 1.5 s.
  • Mathf.Atan2(y, x) (or v.Angle()) turns a direction back into an angle, in all four quadrants.
  • Keep time as the sum of delta (game time), so motion stays deterministic for tests and bots (automation-hooks).

Smoothing toward a target, at any frame rate

x = Mathf.Lerp(x, target, 0.1f) (or x += (target - x) * 0.1f) in _Process closes 10% of the gap per frame: after one second it has closed 95.8% at 30 fps and all of it at 144 fps, and slow motion does not slow it. Give the speed per second instead:

// rate per second: 10% a frame at 60 fps is -ln(0.9) * 60, about 6.3; a half-life of h seconds is ln 2 / h.
float weight = 1f - Mathf.Exp(-Rate * (float)delta);   // or 1f - Mathf.Pow(leftAfterOneSecond, (float)delta)
GlobalPosition = GlobalPosition.Lerp(target.GlobalPosition, weight);

Two frames of half the delta land where one full frame does, so 30, 60 and 144 fps all reach 99.33 of 100 after one second at rate 5. weight = Rate * delta is only a linear approximation (99.58 at 30 fps, 99.38 at 144) and passes the target once Rate * delta exceeds 1; Godot 4.7.2's Camera2D position smoothing computes PositionSmoothingSpeed * delta that way. Each axis or direction may use its own rate: follow vertically only once IsOnFloor(), or catch up faster when falling. The architecture runner warns about a fixed weight in _Process (frame-dependent-lerp).

Easing: bend t, not the value

Any lerp, fade, slide or response curve gets its feel from a function of the 0..1 parameter t with f(0) = 0 and f(1) = 1, applied before the lerp ("Math for Game Programmers: Fast and Funky 1D Nonlinear Transformations", GDC):

Name in the talkFormulaGodot 4.7.2 (checked headless)
smooth start n (ease-in)t * t (n = 2), t * t * t; not Mathf.PowTween.TransitionType.Quad (2), Cubic (3), Quart (4), Quint (5) with EaseType.In; Mathf.Ease(t, 2)
smooth stop n (ease-out)flip, power, flip: 1 - (1 - t) * (1 - t); not a square rootthe same types with EaseType.Out; Mathf.Ease(t, 0.5f)
crossfade start into stop by t(1 - t) * start + t * stopexactly Mathf.SmoothStep(0, 1, t), 3t² - 2t³ (Quad with InOut is a different curve)
arch, bell (out and back to 0)4 * t * (1 - t); smooth start times smooth stop
  • "Quad" is the second power, smaller than "Cubic": name curves by their power, not by the prefix.
  • A higher n arrives more gently: smooth stop 2 ends at zero speed but brakes abruptly, 3 also ends at zero acceleration. Smoothstep still brakes abruptly at the ends.
  • Mathf.Pow with a fractional power is slow (the speaker measured it about ten times slower, some 200 cycles); between two integer powers, blend them: 0.8f * t * t + 0.2f * t * t * t is within 0.008 of t^2.2 on 0..1.

Jumps designed by height and distance

Never pick gravity first and tune a jump speed against it: retuning "floaty" then breaks every gap measured in the levels. Design the arc and derive both (Kyle Pittman, "Building a Better Jump", ${CLAUDE_PLUGIN_ROOT}/docs/gdc/building-a-better-jump.md). Tested in ${CLAUDE_PLUGIN_ROOT}/examples/csharp/src/Example.Core/Platformer/JumpArc.cs:

Design (export these)Launch speed v0Gravity g
height h, time to apex t_h2h / t_h2h / t_h²
height h, distance to apex x_h at foot speed v_x (the fastest in the air)2h v_x / x_h2h v_x² / x_h²

256 px in 0.4 s (or 256 px ahead at 640 px/s) is v0 = 1280 px/s, g = 3200 px/s². Of t_h, x_h and v_x pick two.

  • The jump sets only Velocity.Y (to -v0: y is down); never reset Velocity.X, running speed carries into the air.
  • Pieces, each its own parabola: a heavier fall after the apex (same h, shorter landing distance: FallGravity); a variable height launches for the highest jump and, once the button is let go while rising, switches to ReleaseGravity(minHeight) = v0² / 2h_min until the apex; a double jump is a new arc with its own v0 and g.
  • velocity += GetGravity() * delta before MoveAndSlide() is Euler: the apex misses by v0·dt/2 (21.3 px at 30 Hz, 10.7 at 60, 4.4 at 144 for the jump above), so the jump changes with the physics rate: low with gravity on the take-off tick, high without (the usual if (!IsOnFloor()): 266.7 px in Godot 4.7.2). Move by the tick's average velocity; JumpGravity.Advance also splits the tick that passes the apex, so a heavier fall starts exactly there (switching on the next tick put a fourfold fall 16.6 px off). The wiring, input aside, is tested in ${CLAUDE_PLUGIN_ROOT}/examples/csharp/game/test/gdunit4/JumpArcWiringTest.cs:
public override void _PhysicsProcess(double delta)
{
    float dt = (float)delta;
    bool onFloor = IsOnFloor();
    bool jumped = _jump.Tick(onFloor, Input.IsActionJustPressed(Jump));   // input's forgiveness
    var v = Velocity;
    v.X = Input.GetAxis(Left, Right) * FootSpeed;
    if (jumped) { v.Y = -(float)_arc.LaunchSpeed; _released = false; }
    if (v.Y < 0 && !Input.IsActionPressed(Jump)) _released = true;
    if (onFloor && !jumped) { Velocity = v; MoveAndSlide(); return; }
    float vy = v.Y;
    var through = new Vector2(v.X, _gravity.Advance(ref vy, _released, dt) / dt);   // average velocity this tick
    v.Y = vy;
    Velocity = through;
    MoveAndSlide();
    Velocity = v + (Velocity - through);                  // end velocity, less what a collision took
}

Test it

Math is plain data: test it in a C# unit test (godot-test-loop) with the book's worked examples as expected values, comparing floats with a tolerance (Mathf.IsEqualApprox, or the framework's approximate assertion), never with ==. Take expected values from the worked examples or compute them, never from the exercise key, which has errors (checked in Godot 4.7.2): Ex. 5.2.3 (r = 25 at 75 degrees) answers "(6.4705, 4.8396)", but y is 24.1481; Ex. 5.1.3 gives sin 45 degrees as 0.7070107, not 0.7071068; Ex. 5.2.6's point (5.682, 2.0521) lies at 19.9 degrees, not 60. Figure 2.6 labels the ball-to-wall distance 4.016 where the text says 4.062.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.