Math
trigscript/math is for things that move: a value that follows another, a glide from one
place to another that slows at the end, the distance and the angle between two points.
import { Vec, distance, approach, wrap, lerp, easeOutQuad } from "trigscript/math";
program(() => {
print(`${distance(0, 0, 30, 40)}`); // 50
print(`${approach(10, 50, 15)} ${approach(45, 50, 15)}`); // 25 50
print(`${wrap(-1, 10)} ${wrap(12, 10)}`); // 9 2
print(`${lerp(fixed(0), fixed(100), easeOutQuad(fixed(0.5)))}`); // 75
const v = new Vec(fixed(3), fixed(4));
print(`${v.length()} ${v.add(new Vec(fixed(1), fixed(1))).x}`); // 5 4
});
A location that drifts towards a Marine, eight pixels a frame:
import { approach } from "trigscript/math";
program(async () => {
let x = 0;
let y = 0;
while (true) {
const m = first({ owner: P1, type: units.TerranMarine });
if (m) {
x = approach(x, m.x, 8);
y = approach(y, m.y, 8);
centerLocation(locations.Beacon, x, y);
}
await nextFrame();
}
});
Fractions are the language's fixed numbers, about four decimal places from about −32 768
to 32 767 (Numbers with a fraction).
Angles are radians, 0 to the right and π / 2 down, since y grows down the map. The
functions that can stay whole (approach, wrap, sign, distanceSq, manhattan) do,
and cost less.
| Name | What it gives |
|---|---|
PI, TAU |
π, and a whole turn (2π). |
lerp(a, b, t) |
From a to b by t: a at 0, b at 1. |
inverseLerp(a, b, v) |
Where v is between a and b, as lerp's t. |
remap(v, a1, b1, a2, b2) |
v from the range a1 … b1 into a2 … b2. |
clamp01(t) |
t kept inside 0 … 1. |
approach(current, target, step) |
From current towards target by at most step, never past it. |
wrap(n, size) |
n into 0 … size − 1, going round: wrap(-1, 10) is 9. |
sign(n) |
−1, 0 or 1. |
distance(x1, y1, x2, y2) |
The distance as the crow flies. |
distanceSq(x1, y1, x2, y2) |
The distance squared, whole and cheaper: compare it with a range squared. |
manhattan(x1, y1, x2, y2) |
The distance along the axes, which is what the game's own "nearest" goes by. |
angleTo(x1, y1, x2, y2) |
The angle from one point to the other, −π to π. |
radians(degrees), degrees(radians) |
One unit of angle as the other. |
easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeOutBack, smoothstep |
Easing curves: t from 0 to 1 in, how far along the motion is out. easeOutBack goes a little past the end and comes back. |
new Vec(x, y) |
A point, or a direction with a length. add, sub, scale, dot, length, normalized, angle, rotate, distanceTo and lerp each give a new Vec; Vec.fromAngle(angle, length) makes one from an angle. |