数学辅助
SDK 附带了几个小的数学命名空间——v2 / v3(向量)、col(颜色)、scalar(数值)
——它们操作的正是你组件里用的那套规范类型({x, y} 向量、0..1 的 {r, g, b, a} 颜色)。
每个辅助函数都是纯函数:返回新值,绝不修改入参。至于这些数字意味着什么——世界
单位、设计像素、物理米制以及 Y 轴向上的坐标系——见
变换、单位与坐标系。
v2 覆盖 2D 向量运算;v3 为 3D 提供同样的核心运算。
import { v2 } from 'esengine';
// Move a point by a velocity over dt.const next = v2.add(pos, v2.scale(vel, dt));
// Aim: unit direction from pos to target, then a step of length speed*dt.const dir = v2.normalize(v2.sub(target, pos));const step = v2.scale(dir, speed * dt);
v2.dist(pos, target); // distance (for a range check)v2.fromAngle(Math.PI / 2, 10); // { x: 0, y: 10 }v2.rotate({ x: 1, y: 0 }, Math.PI); // { x: -1, y: 0 }- 四则:
add/sub/scale/mul(逐分量)/neg。 - 点积/长度:
dot、cross、len/len2、dist/dist2。 - 方向:
normalize、angle、fromAngle、rotate、perp(逆时针 90°)。 - 还有:
create、clone、lerp、equals(带 epsilon 的比较)。
col 在 {r, g, b, a}(0..1)约定上构造与混合颜色——白色是 {1, 1, 1, 1}。命名空间
叫 col 是因为裸的 color 名字已经是一个 SDK 导出。
import { col } from 'esengine';
col.rgb(1, 0, 0); // opaque red (0..1 channels)col.from255(255, 128, 0); // from 0..255 channelscol.fromHex('#ff8800'); // #rgb / #rgba / #rrggbb / #rrggbbaa
col.lerp(red, blue, 0.5); // blend halfway (e.g. a damage flash)col.withAlpha(white, 0.3); // fadecol.multiply(base, tint); // per-channel tint- 构造:
create、rgb、from255、fromHex(格式非法时抛错)、clone。 - 混合:
lerp、withAlpha、multiply、scaleRgb;用toHex序列化。
scalar 汇集了玩法与数值调校常用的数值辅助:
import { scalar } from 'esengine';
scalar.clamp01(hp / maxHp); // 0..1scalar.lerp(a, b, 0.25); // interpolatescalar.remap(x, 0, 100, 0, 1); // rescale one range onto anotherscalar.smoothstep(0, 1, t); // eased 0..1 rampscalar.deg2rad(90); // degrees -> radians还有:clamp、inverseLerp、rad2deg、approximately、mod、sign。
Transform.rotation 是四元数;2D 下只会绕 Z 轴旋转,几个导出就覆盖了
角度 ↔ 四元数的往返:
import { quat, quaternionToAngle2D, facingFromQuat, normalizeAngle } from 'esengine';
// Angle -> quaternion. NOTE: the factory takes w FIRST — quat(w, x, y, z).const a = Math.PI / 3;const rot = quat(Math.cos(a / 2), 0, 0, Math.sin(a / 2));
// Quaternion -> angle (radians), from the z/w components.const facing = quaternionToAngle2D(rot.z, rot.w); // Math.PI / 3facingFromQuat(rot.z, rot.w); // same math, the AI/perception spelling
// Wrap to (-π, π] — the shortest signed turn from facing toward a target angle.const delta = normalizeAngle(targetAngle - facing);| 辅助函数 | 说明 |
|---|---|
quat(w?, x?, y?, z?) |
四元数工厂;不传参数得到单位四元数 {w: 1, x: 0, y: 0, z: 0}。 |
quaternionToAngle2D(rz, rw) |
由四元数的 z/w 求 Z 角度(弧度,2 * atan2(z, w))。 |
facingFromQuat(z, w) |
同样的数学,AI/感知模块的命名。 |
normalizeAngle(a) |
把任意角度归一到 (-π, π],用于最短转向比较。 |
如果需要的是方向向量而不是旋转,留在 v2 里就好:fromAngle / angle /
rotate。完整的工作示例(炮塔朝向光标)见
变换、单位与坐标系。