geometry-and-math
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePhaser 4 — Geometry and Math
Phaser 4 — 几何与数学工具
Geom classes (Circle, Ellipse, Line, Polygon, Rectangle, Triangle), intersection tests, and Math utilities (Vector2, Vector3, Matrix4, angles, distances, interpolation, easing, random, snap, clamp).
Related skills: graphics-and-shapes.md, physics-arcade.md
几何类(Circle、Ellipse、Line、Polygon、Rectangle、Triangle)、相交检测,以及数学工具(Vector2、Vector3、Matrix4、角度计算、距离计算、插值、缓动、随机数、对齐、取值限制)。
相关技能:graphics-and-shapes.md、physics-arcade.md
Quick Start
快速入门
js
// Create geometry objects (these are data only, not renderable)
const rect = new Phaser.Geom.Rectangle(10, 20, 200, 100);
const circle = new Phaser.Geom.Circle(400, 300, 50);
const line = new Phaser.Geom.Line(0, 0, 100, 100);
// Point containment
rect.contains(50, 50); // true
circle.contains(410, 310); // true
// Intersection test
Phaser.Geom.Intersects.CircleToRectangle(circle, rect); // boolean
// Math utilities
const v = new Phaser.Math.Vector2(3, 4);
v.length(); // 5
v.normalize(); // {x: 0.6, y: 0.8}
const dist = Phaser.Math.Distance.Between(0, 0, 100, 100);
const angle = Phaser.Math.Angle.Between(0, 0, 100, 100);
const clamped = Phaser.Math.Clamp(150, 0, 100); // 100js
// 创建几何对象(仅存储数据,不可渲染)
const rect = new Phaser.Geom.Rectangle(10, 20, 200, 100);
const circle = new Phaser.Geom.Circle(400, 300, 50);
const line = new Phaser.Geom.Line(0, 0, 100, 100);
// 点包含检测
rect.contains(50, 50); // 返回true
circle.contains(410, 310); // 返回true
// 相交检测
Phaser.Geom.Intersects.CircleToRectangle(circle, rect); // 返回布尔值
// 数学工具使用
const v = new Phaser.Math.Vector2(3, 4);
v.length(); // 返回5
v.normalize(); // 返回{x: 0.6, y: 0.8}
const dist = Phaser.Math.Distance.Between(0, 0, 100, 100);
const angle = Phaser.Math.Angle.Between(0, 0, 100, 100);
const clamped = Phaser.Math.Clamp(150, 0, 100); // 返回100Core Concepts
核心概念
Geometry objects are pure data containers holding coordinates and dimensions. They are NOT game objects and cannot be added to the display list. To render geometry, use the Graphics game object or Shape game objects (see graphics-and-shapes.md).
Every geom class has a property set to a constant for fast type checks.
typePhaser.GeomAll geom classes share a common instance method pattern:
- -- point-in-shape test
contains(x, y) - -- point at normalized position (0-1) on perimeter
getPoint(position, output?) - -- evenly spaced points on perimeter
getPoints(quantity, stepRate?, output?) - -- random point inside the shape
getRandomPoint(output?) - -- reset all properties
setTo(...) - -- zero out the shape
setEmpty() - -- move origin/center
setPosition(x, y)
Each geom type also has a folder of static helper functions (e.g., , ).
Phaser.Geom.Rectangle.ContainsPhaser.Geom.Circle.Area几何对象是纯数据容器,仅存储坐标和尺寸信息。它们不是游戏对象,无法添加到显示列表中。若要渲染几何图形,请使用Graphics游戏对象或Shape游戏对象(详见graphics-and-shapes.md)。
每个几何类都有一个属性,值为常量,用于快速类型检查。
typePhaser.Geom所有几何类共享一套通用的实例方法:
- -- 点是否在图形内部的检测
contains(x, y) - -- 获取图形周长上归一化位置(0-1)对应的点
getPoint(position, output?) - -- 获取周长上均匀分布的点
getPoints(quantity, stepRate?, output?) - -- 获取图形内部的随机点
getRandomPoint(output?) - -- 重置所有属性
setTo(...) - -- 将图形置为空(尺寸归零)
setEmpty() - -- 移动图形的原点/中心点
setPosition(x, y)
每个几何类型还拥有一个静态辅助函数文件夹(例如、)。
Phaser.Geom.Rectangle.ContainsPhaser.Geom.Circle.AreaGeometry Classes
几何类
| Class | Namespace | Constructor | Key Properties |
|---|---|---|---|
| Circle | | | |
| Ellipse | | | |
| Line | | | |
| Polygon | | | |
| Rectangle | | | |
| Triangle | | | |
| 类名 | 命名空间 | 构造函数 | 核心属性 |
|---|---|---|---|
| Circle | | | |
| Ellipse | | | |
| Line | | | |
| Polygon | | | |
| Rectangle | | | |
| Triangle | | | |
Rectangle Static Helpers
Rectangle静态辅助函数
Phaser.Geom.Rectangle.*Phaser.Geom.Rectangle.*Circle Static Helpers
Circle静态辅助函数
Phaser.Geom.Circle.*Phaser.Geom.Circle.*Line Static Helpers
Line静态辅助函数
Phaser.Geom.Line.*Phaser.Geom.Line.*Triangle Static Helpers
Triangle静态辅助函数
Phaser.Geom.Triangle.*Phaser.Geom.Triangle.*Polygon Input Formats
Polygon输入格式
The Polygon constructor accepts multiple formats for the argument:
points- Space-separated string:
'40 0 40 20 100 20 100 80' - Array of objects
{x, y} - Flat number array:
[x1, y1, x2, y2, ...] - Array of sub-arrays
[x, y]
Polygon构造函数的参数支持多种格式:
points- 空格分隔字符串:
'40 0 40 20 100 20 100 80' - 对象数组
{x, y} - 扁平化数字数组:
[x1, y1, x2, y2, ...] - 子数组组成的数组
[x, y]
Intersection Tests
相交检测
All under .
Phaser.Geom.Intersects所有相交检测函数都在命名空间下。
Phaser.Geom.IntersectsBoolean Tests (return true
/false
)
truefalse布尔值检测(返回true
/false
)
truefalse| Function | Description |
|---|---|
| Two circles overlap |
| Circle overlaps rectangle |
| Line segment intersects circle |
| Two line segments cross; writes point to |
| Line segment intersects rectangle |
| Point lies on/near line |
| Point lies on finite line segment |
| Two rectangles overlap |
| Rectangle overlaps triangle |
| Rectangle overlaps LRTB bounds |
| Triangle overlaps circle |
| Triangle intersects line |
| Two triangles overlap |
| 函数 | 描述 |
|---|---|
| 两个圆形是否重叠 |
| 圆形与矩形是否重叠 |
| 线段与圆形是否相交 |
| 两条线段是否交叉;将交点写入 |
| 线段与矩形是否相交 |
| 点是否在直线上/附近 |
| 点是否在有限线段上 |
| 两个矩形是否重叠 |
| 矩形与三角形是否重叠 |
| 矩形是否与LRTB边界重叠 |
| 三角形与圆形是否重叠 |
| 三角形与直线是否相交 |
| 两个三角形是否重叠 |
Get Intersection Points (return Vector2[]
)
Vector2[]获取交点(返回Vector2[]
)
Vector2[]| Function | Description |
|---|---|
| Intersection points of two circles |
| Points where circle meets rectangle edges |
| Points where line crosses circle |
| Single intersection point of two lines |
| Intersection with a series of points forming edges |
| Closest intersection with polygon edges |
| Points where line crosses rectangle |
| Ray-cast from point to polygon edges |
| Overlapping rectangle region |
| Edge intersection points |
| Edge intersection points |
| Edge intersection points |
| Edge intersection points |
| Edge intersection points |
| 函数 | 描述 |
|---|---|
| 两个圆形的交点 |
| 圆形与矩形边缘的交点 |
| 直线与圆形的交点 |
| 两条直线的交点 |
| 直线与一系列点组成的边的交点 |
| 直线与多边形边缘的最近交点 |
| 直线与矩形的交点 |
| 从点到多边形边缘的射线交点 |
| 两个矩形的重叠区域 |
| 两个矩形边缘的交点 |
| 矩形与三角形边缘的交点 |
| 三角形与圆形边缘的交点 |
| 三角形与直线的交点 |
| 两个三角形边缘的交点 |
Math Functions by Category
按类别划分的数学函数
All under unless noted.
Phaser.Math除非特别说明,所有函数都在命名空间下。
Phaser.MathConstants
常量
| Constant | Value |
|---|---|
| PI * 2 (v4 addition) |
| PI / 2 |
| 1.0e-6 |
| PI / 180 |
| 180 / PI |
| Global |
| 常量 | 值 |
|---|---|
| PI * 2(v4新增) |
| PI / 2 |
| 1.0e-6 |
| PI / 180 |
| 180 / PI |
| 全局 |
Angle Functions (Phaser.Math.Angle.*
)
Phaser.Math.Angle.*角度函数(Phaser.Math.Angle.*
)
Phaser.Math.Angle.*| Function | Description |
|---|---|
| Angle in radians between two points |
| Same, taking |
| Angle from vertical axis |
| Same, taking objects |
| Convert to counter-clockwise |
| Clockwise angular distance |
| Counter-clockwise angular distance |
| Shortest angular distance (signed) |
| Normalize to [0, 2PI) |
| Random angle in radians |
| Random angle in degrees |
| Reverse (add PI) |
| Step toward target angle |
| Shortest difference in degrees |
| Wrap to (-PI, PI] |
| Wrap to (-180, 180] |
| 函数 | 描述 |
|---|---|
| 两点之间的弧度角度 |
| 同上,参数为 |
| 与垂直轴的夹角 |
| 同上,参数为对象 |
| 转换为逆时针角度 |
| 顺时针方向的角度距离 |
| 逆时针方向的角度距离 |
| 最短角度距离(带符号) |
| 将角度归一化到[0, 2PI)范围 |
| 随机弧度角度 |
| 随机角度(度数) |
| 反转角度(加PI) |
| 逐步向目标角度旋转 |
| 角度的最小差值(度数) |
| 将角度包裹到(-PI, PI]范围 |
| 将角度包裹到(-180, 180]范围 |
Distance Functions (Phaser.Math.Distance.*
)
Phaser.Math.Distance.*距离函数(Phaser.Math.Distance.*
)
Phaser.Math.Distance.*| Function | Description |
|---|---|
| Euclidean distance |
| Same, taking |
| Squared distance (avoids sqrt) |
| Chebyshev (chessboard) distance |
| Minkowski distance with custom power |
| Manhattan/taxicab distance |
| Squared Euclidean distance |
| 函数 | 描述 |
|---|---|
| 欧几里得距离 |
| 同上,参数为 |
| 平方距离(避免开根号运算) |
| 切比雪夫(棋盘式)距离 |
| 自定义幂次的闵可夫斯基距离 |
| 曼哈顿/出租车距离 |
| 平方欧几里得距离 |
Interpolation (Phaser.Math.Interpolation.*
)
Phaser.Math.Interpolation.*插值函数(Phaser.Math.Interpolation.*
)
Phaser.Math.Interpolation.*| Function | Description |
|---|---|
| Bezier curve through control points |
| Catmull-Rom spline through points |
| Cubic Bezier between four values |
| Linear through array of values |
| Quadratic Bezier |
| Hermite smooth step |
| Ken Perlin's smoother step |
| 函数 | 描述 |
|---|---|
| 通过控制点的贝塞尔曲线插值 |
| 通过点的Catmull-Rom样条插值 |
| 四个值之间的三次贝塞尔插值 |
| 数组值之间的线性插值 |
| 二次贝塞尔插值 |
| 埃尔米特平滑步进插值 |
| Ken Perlin的更平滑步进插值 |
Snap Functions (Phaser.Math.Snap.*
)
Phaser.Math.Snap.*对齐函数(Phaser.Math.Snap.*
)
Phaser.Math.Snap.*| Function | Description |
|---|---|
| Snap to nearest increment |
| Snap down to increment |
| Snap up to increment |
| 函数 | 描述 |
|---|---|
| 将值对齐到最近的增量 |
| 将值向下对齐到增量 |
| 将值向上对齐到增量 |
Fuzzy Comparison (Phaser.Math.Fuzzy.*
)
Phaser.Math.Fuzzy.*模糊比较(Phaser.Math.Fuzzy.*
)
Phaser.Math.Fuzzy.*| Function | Description |
|---|---|
| a approximately equals b |
| a < b within epsilon |
| a > b within epsilon |
| Fuzzy ceiling |
| Fuzzy floor |
| 函数 | 描述 |
|---|---|
| a与b是否近似相等 |
| a是否在epsilon范围内小于b |
| a是否在epsilon范围内大于b |
| 模糊向上取整 |
| 模糊向下取整 |
Easing Functions (Phaser.Math.Easing.*
)
Phaser.Math.Easing.*缓动函数(Phaser.Math.Easing.*
)
Phaser.Math.Easing.*Each type has , , variants. Used primarily by tweens (pass string names like ).
.In.Out.InOut'Sine.easeOut'| Type | String Keys |
|---|---|
| Back | |
| Bounce | |
| Circular | |
| Cubic | |
| Elastic | |
| Expo | |
| Linear | |
| Quadratic | |
| Quartic | |
| Quintic | |
| Sine | |
| Stepped | |
Power aliases: = Linear, = Quad.Out, = Cubic.Out, = Quart.Out, = Quint.Out.
Power0Power1Power2Power3Power4Short names also work: = Quad.Out, = Sine.Out, etc.
'Quad''Sine'每种类型都有、、变体。主要用于补间动画(传入字符串名称,如)。
.In.Out.InOut'Sine.easeOut'| 类型 | 字符串键 |
|---|---|
| Back | |
| Bounce | |
| Circular | |
| Cubic | |
| Elastic | |
| Expo | |
| Linear | |
| Quadratic | |
| Quartic | |
| Quintic | |
| Sine | |
| Stepped | |
幂别名: = Linear, = Quad.Out, = Cubic.Out, = Quart.Out, = Quint.Out。
Power0Power1Power2Power3Power4短名称同样有效: = Quad.Out, = Sine.Out等。
'Quad''Sine'Core Math Helpers (directly on Phaser.Math
)
Phaser.Math核心数学辅助函数(直接在Phaser.Math
下)
Phaser.Math| Function | Description |
|---|---|
| Random integer in [min, max] |
| Random float in [min, max] |
| Constrain value to range |
| Wrap value within range |
| Check if a is within tolerance of b |
| Value as percentage of range |
| Value from percentage of range |
| Convert degrees to radians |
| Convert radians to degrees |
| Lerp between two values |
| Lerp between two Vector2Like objects |
| Hermite smooth step |
| Perlin smoother step |
| Mean of number array |
| Median of number array |
| Ceil to decimal place |
| Floor to decimal place |
| Round to decimal place |
| Round away from zero |
| Add clamped to max |
| Subtract clamped to min |
| Absolute difference |
| Integer is even |
| Strictly even (not zero) |
| Factorial |
| Rotate point around origin |
| Rotate point around custom center |
| Rotate at fixed distance |
| Full 2D transform |
| Speed from distance and time |
| Set vector to random unit direction |
| 函数 | 描述 |
|---|---|
| [min, max]范围内的随机整数 |
| [min, max]范围内的随机浮点数 |
| 将值限制在指定范围内 |
| 将值包裹在指定范围内 |
| 检查a是否在b的容差范围内 |
| 值在范围内的百分比 |
| 根据百分比获取范围内对应的值 |
| 将度数转换为弧度 |
| 将弧度转换为度数 |
| 两个值之间的线性插值 |
| 两个Vector2Like对象之间的线性插值 |
| 埃尔米特平滑步进 |
| Perlin更平滑步进 |
| 数字数组的平均值 |
| 数字数组的中位数 |
| 将值向上取整到指定小数位 |
| 将值向下取整到指定小数位 |
| 将值四舍五入到指定小数位 |
| 向远离零的方向取整 |
| 增加值但不超过最大值 |
| 减少值但不低于最小值 |
| 绝对值差 |
| 整数是否为偶数 |
| 是否为严格偶数(非零) |
| 阶乘 |
| 绕原点旋转点 |
| 绕自定义中心点旋转点 |
| 保持固定距离旋转点 |
| 完整的2D变换 |
| 根据距离和时间计算速度 |
| 将向量设置为随机单位方向 |
Power-of-Two (Phaser.Math.Pow2.*
)
Phaser.Math.Pow2.*2的幂相关函数(Phaser.Math.Pow2.*
)
Phaser.Math.Pow2.*| Function | Description |
|---|---|
| Next power of two >= value |
| Check if value is power of two |
| Check if both dimensions are power of two |
| 函数 | 描述 |
|---|---|
| 大于等于value的下一个2的幂 |
| 检查value是否为2的幂 |
| 检查宽高是否均为2的幂 |
Vector2 Quick Reference
Vector2速查
Phaser.Math.Vector2Constructor: or . If only given, defaults to .
new Vector2(x?, y?)new Vector2({x, y})xyx| Method | Returns | Description |
|---|---|---|
| this | Set components |
| this | Set from angle + length |
| this | Copy from Vector2Like |
| Vector2 | New copy |
| this | Component-wise add/subtract |
| this | Component-wise multiply/divide |
| this | Multiply both components by scalar |
| this | Flip sign of both components |
| this | Set length to 1 |
| this | Perpendicular (right-hand rule) |
| this | Perpendicular (left-hand rule) |
| this | Cap length to max |
| this | Scale to exact length |
| number | Magnitude |
| number | Squared magnitude (no sqrt) |
| number | Distance to another vector |
| number | Squared distance |
| number | Dot product |
| number | 2D cross product (scalar) |
| number | Angle in radians from positive x-axis |
| this | Rotate to angle, keeping length |
| this | Rotate by delta radians |
| this | Linear interpolate toward src |
| this | Reflect off surface normal |
| this | Mirror across axis vector |
| this | Project onto another vector |
| boolean | Exact equality |
| boolean | Approximate equality |
| this | Component transforms |
| this | Set to (0, 0) |
| this | Transform by Matrix3 |
| this | Transform by Matrix4 |
Static: , , , , , .
Vector2.ZEROVector2.RIGHTVector2.LEFTVector2.UPVector2.DOWNVector2.ONEPhaser.Math.Vector2构造函数: 或 。若仅传入,默认等于。
new Vector2(x?, y?)new Vector2({x, y})xyx| 方法 | 返回值 | 描述 |
|---|---|---|
| this | 设置向量分量 |
| this | 通过角度+长度设置向量 |
| this | 从Vector2Like对象复制值 |
| Vector2 | 创建向量副本 |
| this | 分量级加减 |
| this | 分量级乘除 |
| this | 两个分量乘以标量 |
| this | 翻转两个分量的符号 |
| this | 将向量长度设置为1 |
| this | 生成右手规则的垂直向量 |
| this | 生成左手规则的垂直向量 |
| this | 将向量长度限制为max |
| this | 将向量缩放到指定长度 |
| number | 向量的模长 |
| number | 向量模长的平方(避免开根号) |
| number | 到另一个向量的距离 |
| number | 到另一个向量的平方距离 |
| number | 点积 |
| number | 2D叉积(标量) |
| number | 与x轴正方向的夹角(弧度) |
| this | 旋转到指定角度,保持长度不变 |
| this | 旋转delta弧度 |
| this | 向目标向量线性插值 |
| this | 沿表面法线反射向量 |
| this | 沿轴向量镜像向量 |
| this | 将向量投影到另一个向量上 |
| boolean | 精确相等判断 |
| boolean | 近似相等判断 |
| this | 分量级变换 |
| this | 将向量设置为(0, 0) |
| this | 通过Matrix3变换向量 |
| this | 通过Matrix4变换向量 |
静态常量:, , , , , 。
Vector2.ZEROVector2.RIGHTVector2.LEFTVector2.UPVector2.DOWNVector2.ONEVector3 Quick Reference
Vector3速查
Phaser.Math.Vector3Constructor: or .
new Vector3(x?, y?, z?)new Vector3({x, y, z})Key methods (same patterns as Vector2 plus): , , , , , , , , , , , , , , , , , , .
up()min(v)max(v)addVectors(a, b)subVectors(a, b)crossVectors(a, b)cross(v)addScalar(s)addScale(v, scale)fromArray(array, offset?)setFromMatrixPosition(mat4)setFromMatrixColumn(mat4, index)applyMatrix3(mat)applyMatrix4(mat)transformCoordinates(mat)transformQuat(q)project(mat)projectViewMatrix(view, proj)unproject(viewport, invProjView)Phaser.Math.Vector3构造函数: 或 。
new Vector3(x?, y?, z?)new Vector3({x, y, z})核心方法(与Vector2模式相同,新增以下方法):, , , , , , , , , , , , , , , , , , 。
up()min(v)max(v)addVectors(a, b)subVectors(a, b)crossVectors(a, b)cross(v)addScalar(s)addScale(v, scale)fromArray(array, offset?)setFromMatrixPosition(mat4)setFromMatrixColumn(mat4, index)applyMatrix3(mat)applyMatrix4(mat)transformCoordinates(mat)transformQuat(q)project(mat)projectViewMatrix(view, proj)unproject(viewport, invProjView)Matrix4 Quick Reference
Matrix4速查
Phaser.Math.Matrix4Float32Array(16)Constructor: -- copies from existing Matrix4, or defaults to identity.
new Matrix4(m?)Key methods: , , , , , , , , , , , , , , , , , , , , , , , , .
clone()set(src)copy(src)identity()transpose()invert()adjoint()determinant()multiply(src)multiplyLocal(src)translate(v)scale(v)rotate(angle, axis)rotateX(angle)rotateY(angle)rotateZ(angle)fromRotationTranslation(q, v)fromQuat(q)frustum(...)perspective(fovy, aspect, near, far)perspectiveLH(width, height, near, far)ortho(left, right, bottom, top, near, far)lookAt(eye, center, up)lookAtRH(eye, target, up)setWorldMatrix(rotation, position, scale, viewMatrix?, projectionMatrix?)Also: -- 3x3 matrix for 2D transforms and normal matrices.
Phaser.Math.Matrix3Phaser.Math.Matrix4Float32Array(16)构造函数: —— 从现有Matrix4复制,或默认创建单位矩阵。
new Matrix4(m?)核心方法:, , , , , , , , , , , , , , , , , , , , , , , , 。
clone()set(src)copy(src)identity()transpose()invert()adjoint()determinant()multiply(src)multiplyLocal(src)translate(v)scale(v)rotate(angle, axis)rotateX(angle)rotateY(angle)rotateZ(angle)fromRotationTranslation(q, v)fromQuat(q)frustum(...)perspective(fovy, aspect, near, far)perspectiveLH(width, height, near, far)ortho(left, right, bottom, top, near, far)lookAt(eye, center, up)lookAtRH(eye, target, up)setWorldMatrix(rotation, position, scale, viewMatrix?, projectionMatrix?)此外还有: —— 用于2D变换和法向量矩阵的3x3矩阵。
Phaser.Math.Matrix3RandomDataGenerator
RandomDataGenerator
Phaser.Math.RandomDataGeneratorPhaser.Math.RNDseedjs
const rnd = Phaser.Math.RND; // or new Phaser.Math.RandomDataGenerator(['my-seed'])
rnd.integer(); // random integer in [0, 2^32]
rnd.frac(); // random float in [0, 1)
rnd.between(1, 10); // random integer in [1, 10]
rnd.integerInRange(1, 10); // alias for between
rnd.realInRange(0.5, 1.5); // random float in [0.5, 1.5]
rnd.normal(); // normal distribution around 0
rnd.angle(); // random angle in radians (-PI to PI)
rnd.rotation(); // random rotation in radians (same range)
rnd.pick(array); // random element from array
rnd.weightedPick(array); // weighted toward end of array
rnd.sign(); // -1 or 1
rnd.uuid(); // RFC4122 v4 UUID string
rnd.shuffle(array); // in-place Fisher-Yates shuffle
rnd.state(state?); // get/set serializable state for save/loadCreate reproducible sequences by providing seeds: .
new RandomDataGenerator(['level-42'])Phaser.Math.RandomDataGeneratorPhaser.Math.RNDseedjs
const rnd = Phaser.Math.RND; // 或 new Phaser.Math.RandomDataGenerator(['my-seed'])
rnd.integer(); // [0, 2^32]范围内的随机整数
rnd.frac(); // [0, 1)范围内的随机浮点数
rnd.between(1, 10); // [1, 10]范围内的随机整数
rnd.integerInRange(1, 10); // between的别名
rnd.realInRange(0.5, 1.5); // [0.5, 1.5]范围内的随机浮点数
rnd.normal(); // 以0为中心的正态分布随机数
rnd.angle(); // 随机弧度角度(-PI到PI)
rnd.rotation(); // 随机旋转角度(同上述范围)
rnd.pick(array); // 从数组中随机选取元素
rnd.weightedPick(array); // 偏向数组末尾的加权随机选取
rnd.sign(); // 返回-1或1
rnd.uuid(); // RFC4122 v4格式的UUID字符串
rnd.shuffle(array); // 原地Fisher-Yates洗牌
rnd.state(state?); // 获取/设置可序列化状态,用于保存/加载通过传入种子创建可复现的随机序列:。
new RandomDataGenerator(['level-42'])Color Utilities
颜色工具
Color Class (Phaser.Display.Color
)
Phaser.Display.ColorColor类(Phaser.Display.Color
)
Phaser.Display.ColorA mutable RGBA color representation with automatic conversion to WebGL floats, HSV, CSS strings, and packed integers.
js
// Construction
const color = new Phaser.Display.Color(255, 0, 0, 255); // RGBA (0-255)
// Creation helpers (return Color instances)
const c1 = Phaser.Display.Color.ValueToColor('#ff0000'); // hex string, integer, or object
const c2 = Phaser.Display.Color.HexStringToColor('#ff0000');
const c3 = Phaser.Display.Color.RGBStringToColor('rgb(255,0,0)');
const c4 = Phaser.Display.Color.HSVToRGB(0.5, 1, 1); // returns { r, g, b, color }
// Properties
color.r; color.g; color.b; color.a; // 0-255 integers
color.redGL; color.greenGL; color.blueGL; color.alphaGL; // 0-1 floats (WebGL)
color.color; // packed 24-bit integer (0xRRGGBB)
color.color32; // packed 32-bit integer (0xAARRGGBB)
color.rgba; // CSS string 'rgba(r,g,b,a)'
color.h; color.s; color.v; // HSV representation (read-only, auto-updated)可变的RGBA颜色表示,支持自动转换为WebGL浮点数、HSV、CSS字符串和打包整数。
js
// 构造方式
const color = new Phaser.Display.Color(255, 0, 0, 255); // RGBA(0-255)
// 创建辅助方法(返回Color实例)
const c1 = Phaser.Display.Color.ValueToColor('#ff0000'); // 支持十六进制字符串、整数或对象
const c2 = Phaser.Display.Color.HexStringToColor('#ff0000');
const c3 = Phaser.Display.Color.RGBStringToColor('rgb(255,0,0)');
const c4 = Phaser.Display.Color.HSVToRGB(0.5, 1, 1); // 返回{ r, g, b, color }
// 属性
color.r; color.g; color.b; color.a; // 0-255整数
color.redGL; color.greenGL; color.blueGL; color.alphaGL; // 0-1浮点数(WebGL用)
color.color; // 24位打包整数(0xRRGGBB)
color.color32; // 32位打包整数(0xAARRGGBB)
color.rgba; // CSS格式字符串'rgba(r,g,b,a)'
color.h; color.s; color.v; // HSV表示(只读,自动更新)Color Manipulation
颜色操作
js
// Adjustment methods (amount is typically 0-100, returns the Color instance)
color.brighten(25); // increase brightness
color.saturate(50); // increase saturation
color.desaturate(30); // decrease saturation
color.lighten(20); // increase lightness
color.darken(10); // decrease lightness
// Utility methods
color.random(); // set to random RGB values (optional min/max range)
color.gray(128); // set to grayscale shade (0-255)
// Setting values
color.setTo(255, 128, 0, 255); // RGBA
color.setFromRGB({ r: 255, g: 128, b: 0, a: 255 });
color.setFromHSV(0.1, 0.8, 1.0); // HSV (0-1 range)js
// 调整方法(amount通常为0-100,返回Color实例)
color.brighten(25); // 增加亮度
color.saturate(50); // 增加饱和度
color.desaturate(30); // 降低饱和度
color.lighten(20); // 增加明度
color.darken(10); // 降低明度
// 工具方法
color.random(); // 设置为随机RGB值(可选指定最小/最大范围)
color.gray(128); // 设置为指定灰度值(0-255)
// 设置值
color.setTo(255, 128, 0, 255); // RGBA
color.setFromRGB({ r: 255, g: 128, b: 0, a: 255 });
color.setFromHSV(0.1, 0.8, 1.0); // HSV(0-1范围)Color Interpolation (Phaser.Display.Color.Interpolate
)
Phaser.Display.Color.Interpolate颜色插值(Phaser.Display.Color.Interpolate
)
Phaser.Display.Color.InterpolateInterpolate between colors over a given length. Returns .
{ r, g, b, a, color }js
// Between raw RGB values
const result = Phaser.Display.Color.Interpolate.RGBWithRGB(
255, 0, 0, // start color (r, g, b)
0, 0, 255, // end color (r, g, b)
100, // length (number of steps)
50 // index (current step)
); // returns midpoint purple { r, g, b, a, color }
// Between two Color objects
const mid = Phaser.Display.Color.Interpolate.ColorWithColor(color1, color2, 100, 50);
// HSV interpolation (v4): smooth hue transition
const hsvResult = Phaser.Display.Color.Interpolate.HSVWithHSV(0, 1, 1, 0.5, 1, 1, 100, 50);在指定步数内插值两种颜色。返回。
{ r, g, b, a, color }js
// 原始RGB值之间插值
const result = Phaser.Display.Color.Interpolate.RGBWithRGB(
255, 0, 0, // 起始颜色(r, g, b)
0, 0, 255, // 结束颜色(r, g, b)
100, // 总步数
50 // 当前步骤索引
); // 返回中点紫色{ r, g, b, a, color }
// 两个Color对象之间插值
const mid = Phaser.Display.Color.Interpolate.ColorWithColor(color1, color2, 100, 50);
// HSV插值(v4新增):平滑的色相过渡
const hsvResult = Phaser.Display.Color.Interpolate.HSVWithHSV(0, 1, 1, 0.5, 1, 1, 100, 50);Gotchas
注意事项
-
Geom objects are not game objects. They have no, no
scenefrom the display list, no texture. Use Graphics or Shape game objects to render them.setPosition -
Point class removed in v4. Useor plain
Phaser.Math.Vector2objects instead. The{x, y}(3) exists but the Point class does not.GEOM_CONST.POINT -
Angles are in radians throughout the math API. Useand
Phaser.Math.DegToRad()for conversion. TheRadToDeg()constant (2 * PI) is new in v4.Phaser.Math.TAU -
Vector2 methods mutate in place and returnfor chaining. Call
thisfirst if you need to preserve the original:.clone().const result = v.clone().add(other) -
Squared distance is faster than Euclidean distance (avoids). Use
Math.sqrtorDistance.Squaredfor comparisons where the actual distance value is not needed.vec.distanceSq() -
Intersection Get functions allocate arrays.* Pass a reusablearray to avoid garbage collection pressure in hot loops.
out -
EaseMap short names default to thevariant.
.Outmeans'Quad', notQuadratic.Out. Use full string keys likeQuadratic.Infor other variants.'Quad.easeIn' -
RandomDataGenerator state is serializable. Callto get a string you can store, and
rnd.state()to restore it for deterministic replay.rnd.state(savedString) -
Polygon.contains uses ray-casting (even/odd rule). Complex self-intersecting polygons may give unexpected results.
-
Matrix4.val is a Float32Array. Access elements directly viausing column-major order (OpenGL convention).
mat.val[index]
-
几何对象不是游戏对象。它们没有属性,没有显示列表的
scene方法,也没有纹理。请使用Graphics或Shape游戏对象来渲染它们。setPosition -
v4中移除了Point类。请使用或普通
Phaser.Math.Vector2对象替代。{x, y}(值为3)仍然存在,但Point类已被移除。GEOM_CONST.POINT -
数学API中的角度均为弧度。使用和
Phaser.Math.DegToRad()进行转换。RadToDeg()常量(2 * PI)是v4新增的。Phaser.Math.TAU -
Vector2方法会原地修改向量并返回以支持链式调用。如果需要保留原始向量,请先调用
this:.clone()。const result = v.clone().add(other) -
平方距离比欧几里得距离更快(避免运算)。当不需要实际距离值,仅用于比较时,请使用
Math.sqrt或Distance.Squared。vec.distanceSq() -
相交检测的Get*函数会分配数组。在高频循环中,请传入可复用的数组以避免垃圾回收压力。
out -
EaseMap短名称默认对应.Out变体。表示
'Quad',而非Quadratic.Out。如需其他变体,请使用完整字符串键,如Quadratic.In。'Quad.easeIn' -
RandomDataGenerator的状态可序列化。调用获取可存储的字符串,调用
rnd.state()恢复状态以实现确定性重放。rnd.state(savedString) -
Polygon.contains使用射线投射法(奇偶规则)。复杂的自相交多边形可能会产生意外结果。
-
Matrix4.val是Float32Array。使用列主序(OpenGL约定)通过直接访问元素。
mat.val[index]
Source File Map
源文件映射
| Area | Path |
|---|---|
| Geom classes | |
| Geom constants | |
| Intersection tests | |
| Vector2 | |
| Vector3 | |
| Vector4 | |
| Matrix3 | |
| Matrix4 | |
| Quaternion | |
| Euler | |
| Angle functions | |
| Distance functions | |
| Easing functions | |
| Fuzzy comparison | |
| Interpolation | |
| Snap functions | |
| Power-of-two | |
| RandomDataGenerator | |
| Math constants | |
| Color class | |
| Color utilities | |
| Core math helpers | |
| 领域 | 路径 |
|---|---|
| 几何类 | |
| 几何常量 | |
| 相交检测 | |
| Vector2 | |
| Vector3 | |
| Vector4 | |
| Matrix3 | |
| Matrix4 | |
| Quaternion | |
| Euler | |
| 角度函数 | |
| 距离函数 | |
| 缓动函数 | |
| 模糊比较 | |
| 插值函数 | |
| 对齐函数 | |
| 2的幂相关 | |
| RandomDataGenerator | |
| 数学常量 | |
| Color类 | |
| 颜色工具 | |
| 核心数学辅助函数 | |