跳转到内容

数学辅助

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
  • 点积/长度:dotcrosslen / len2dist / dist2
  • 方向:normalizeanglefromAnglerotateperp(逆时针 90°)。
  • 还有:createclonelerpequals(带 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 channels
col.fromHex('#ff8800'); // #rgb / #rgba / #rrggbb / #rrggbbaa
col.lerp(red, blue, 0.5); // blend halfway (e.g. a damage flash)
col.withAlpha(white, 0.3); // fade
col.multiply(base, tint); // per-channel tint
  • 构造:creatergbfrom255fromHex(格式非法时抛错)、clone
  • 混合:lerpwithAlphamultiplyscaleRgb;用 toHex 序列化。

scalar 汇集了玩法与数值调校常用的数值辅助:

import { scalar } from 'esengine';
scalar.clamp01(hp / maxHp); // 0..1
scalar.lerp(a, b, 0.25); // interpolate
scalar.remap(x, 0, 100, 0, 1); // rescale one range onto another
scalar.smoothstep(0, 1, t); // eased 0..1 ramp
scalar.deg2rad(90); // degrees -> radians

还有:clampinverseLerprad2degapproximatelymodsign

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 / 3
facingFromQuat(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。完整的工作示例(炮塔朝向光标)见 变换、单位与坐标系

  • 变换、单位与坐标系——这些数字的含义: 世界单位 = 设计像素、物理米制、Y 轴向上,以及用四元数旋转实体。
  • 物理——这些辅助函数最终喂给的米制单位面。