pixijs-math
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePixiJS exposes lightweight math primitives (Point, Matrix, shape classes) used throughout the library for transforms, hit testing, and coordinate conversion. Import to add vector operations (add, dot, magnitude, reflect) and Rectangle intersection/union helpers.
pixi.js/math-extrasPixiJS 提供了轻量级的数学基元(Point、Matrix、形状类),整个库中都使用它们来处理变换、命中测试和坐标转换。导入 可添加向量运算(add、dot、magnitude、reflect)以及Rectangle的相交/合并辅助工具。
pixi.js/math-extrasQuick Start
快速开始
ts
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
app.stage.addChild(parent);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
const globalPt = child.toGlobal(new Point(0, 0));
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
const world = m.apply(new Point(10, 20));
const hitArea = new Rectangle(0, 0, 200, 100);
console.log(hitArea.contains(50, 50));Related skills: (transform properties), (hitArea usage), (culling with Rectangle).
pixijs-scene-containerpixijs-eventspixijs-scene-core-conceptsts
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
app.stage.addChild(parent);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
const globalPt = child.toGlobal(new Point(0, 0));
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
const world = m.apply(new Point(10, 20));
const hitArea = new Rectangle(0, 0, 200, 100);
console.log(hitArea.contains(50, 50));相关技能: (变换属性)、(hitArea 使用)、(使用Rectangle进行裁剪)。
pixijs-scene-containerpixijs-eventspixijs-scene-core-conceptsCore Patterns
核心模式
Point and ObservablePoint
Point与ObservablePoint
Point is a simple {x, y} value type. ObservablePoint fires a callback when x or y changes; it is used internally by Container's position, scale, pivot, origin, and skew.
ts
import { Point } from "pixi.js";
const p = new Point(10, 20);
p.set(30, 40); // set both
p.set(50); // x=50, y=50
const clone = p.clone();
console.log(p.equals(clone)); // true
p.copyFrom({ x: 1, y: 2 }); // accepts any PointData
// Point.shared: temporary point, reset to (0,0) on each access
const temp = Point.shared;
temp.set(100, 200);
// do not store a reference to Point.sharedContainer properties like , , , , and are ObservablePoints. Setting or on them triggers transform recalculation automatically.
positionscalepivotoriginskew.x.yts
import { Container } from "pixi.js";
const obj = new Container();
obj.position.set(100, 200); // triggers observer -> marks transform dirty
obj.position.x = 150; // also triggers observerPoint是一种简单的{x, y}值类型。ObservablePoint会在x或y值变化时触发回调,它被Container的position、scale、pivot、origin和skew属性内部使用。
ts
import { Point } from "pixi.js";
const p = new Point(10, 20);
p.set(30, 40); // 设置两个值
p.set(50); // x=50, y=50
const clone = p.clone();
console.log(p.equals(clone)); // true
p.copyFrom({ x: 1, y: 2 }); // 接受任何PointData类型
// Point.shared: 临时点,每次访问时会重置为(0,0)
const temp = Point.shared;
temp.set(100, 200);
// 不要存储Point.shared的引用Container的position、scale、pivot、origin和skew等属性都是ObservablePoint。修改它们的.x或.y属性会自动触发变换重新计算。
ts
import { Container } from "pixi.js";
const obj = new Container();
obj.position.set(100, 200); // 触发观察者 -> 标记变换为脏状态
obj.position.x = 150; // 同样会触发观察者Matrix (2D affine transform)
Matrix(2D仿射变换)
Matrix represents a 3x3 affine transform: . It supports translate, scale, rotate, append, prepend, invert, and decompose.
| a c tx | b d ty | 0 0 1 |ts
import { Matrix, Point } from "pixi.js";
// Build a transform
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
// Transform a point (local -> parent space)
const local = new Point(10, 20);
const world = m.apply(local);
// Inverse transform (parent -> local space)
const backToLocal = m.applyInverse(world);
// Combine matrices
const a = new Matrix().translate(50, 0);
const b = new Matrix().rotate(Math.PI / 2);
a.append(b); // a = a * b
// Decompose into position/scale/rotation/skew
const transform = {
position: new Point(),
scale: new Point(),
pivot: new Point(),
skew: new Point(),
rotation: 0,
};
m.decompose(transform);
console.log(transform.rotation); // ~0.785 (PI/4)
// Shared temporary matrix (reset on each access)
const temp = Matrix.shared;
// IDENTITY is read-only reference
const isDefault = m.equals(Matrix.IDENTITY);Matrix代表一个3x3的仿射变换:。它支持平移、缩放、旋转、追加、前置、反转和分解操作。
| a c tx | b d ty | 0 0 1 |ts
import { Matrix, Point } from "pixi.js";
// 构建变换矩阵
const m = new Matrix()
.translate(100, 50)
.rotate(Math.PI / 4)
.scale(2, 2);
// 变换点(局部 -> 父级空间)
const local = new Point(10, 20);
const world = m.apply(local);
// 逆变换(父级 -> 局部空间)
const backToLocal = m.applyInverse(world);
// 合并矩阵
const a = new Matrix().translate(50, 0);
const b = new Matrix().rotate(Math.PI / 2);
a.append(b); // a = a * b
// 分解为位置/缩放/旋转/倾斜
const transform = {
position: new Point(),
scale: new Point(),
pivot: new Point(),
skew: new Point(),
rotation: 0,
};
m.decompose(transform);
console.log(transform.rotation); // ~0.785 (PI/4)
// 共享临时矩阵(每次访问时重置)
const temp = Matrix.shared;
// IDENTITY是只读引用
const isDefault = m.equals(Matrix.IDENTITY);Coordinate transforms via Container
通过Container进行坐标变换
Containers provide , , and for coordinate conversion.
toGlobaltoLocalgetGlobalPositionts
import { Container, Point } from "pixi.js";
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
// Local point in child's space -> global (world) space
const globalPt = child.toGlobal(new Point(0, 0));
// globalPt = { x: 200, y: 200 } (100 + 50*2, 100 + 50*2)
// Global point -> child's local space
const localPt = child.toLocal(new Point(200, 200));
// localPt = { x: 0, y: 0 }
// Convert between two containers
const other = new Container();
other.position.set(300, 300);
const ptInOther = child.toLocal(new Point(10, 10), other);Container提供了、和方法用于坐标转换。
toGlobaltoLocalgetGlobalPositionts
import { Container, Point } from "pixi.js";
const parent = new Container();
parent.position.set(100, 100);
parent.scale.set(2);
const child = new Container();
child.position.set(50, 50);
parent.addChild(child);
// 子容器空间中的局部点 -> 全局(世界)空间
const globalPt = child.toGlobal(new Point(0, 0));
// globalPt = { x: 200, y: 200 } (100 + 50*2, 100 + 50*2)
// 全局点 -> 子容器的局部空间
const localPt = child.toLocal(new Point(200, 200));
// localPt = { x: 0, y: 0 }
// 在两个容器之间转换
const other = new Container();
other.position.set(300, 300);
const ptInOther = child.toLocal(new Point(10, 10), other);Shapes and hit testing
形状与命中测试
Rectangle, Circle, Ellipse, Polygon, RoundedRectangle, and Triangle all implement for point-in-shape tests, plus and . They can be used as on containers for custom interaction regions.
contains(x, y)getBounds(out?)strokeContains(x, y, width, alignment?)hitAreats
import { Rectangle, Circle, Polygon, Container } from "pixi.js";
const rect = new Rectangle(0, 0, 200, 100);
rect.contains(50, 50); // true
rect.contains(300, 50); // false
rect.left; // 0
rect.right; // 200
rect.top; // 0
rect.bottom; // 100
rect.isEmpty(); // false (Rectangle.EMPTY returns a fresh empty rect)
// Native Rectangle-to-Rectangle methods (no math-extras needed)
const other = new Rectangle(50, 50, 100, 100);
rect.containsRect(other); // true if `other` is fully inside `rect`
rect.intersects(other); // boolean: do they overlap at all?
rect.intersects(other, matrix); // overlap after transforming `other`
// Stroke hit testing (alignment: 1 = inner, 0.5 = centered, 0 = outer)
rect.strokeContains(0, 50, 4); // true if (0,50) lies on a 4px centered stroke
const circle = new Circle(100, 100, 50);
circle.strokeContains(150, 100, 4, 1); // inner-aligned stroke check
// getBounds works on every shape (returns a Rectangle, accepts an out param)
const bounds = circle.getBounds();
const reused = new Rectangle();
new Polygon([0, 0, 100, 0, 50, 100]).getBounds(reused);
// Use as hit area for interaction
const button = new Container();
button.hitArea = new Rectangle(0, 0, 200, 50);
button.eventMode = "static";
button.on("pointerdown", () => {
/* clicked */
});Do not confuse native (returns ) with math-extras (returns a describing the overlap area).
Rectangle.intersects(other)booleanintersection(other)RectangleRectangle、Circle、Ellipse、Polygon、RoundedRectangle和Triangle都实现了方法用于点是否在形状内的测试,还包括和方法。它们可以作为容器的属性,用于自定义交互区域。
contains(x, y)getBounds(out?)strokeContains(x, y, width, alignment?)hitAreats
import { Rectangle, Circle, Polygon, Container } from "pixi.js";
const rect = new Rectangle(0, 0, 200, 100);
rect.contains(50, 50); // true
rect.contains(300, 50); // false
rect.left; // 0
rect.right; // 200
rect.top; // 0
rect.bottom; // 100
rect.isEmpty(); // false (Rectangle.EMPTY返回一个新的空矩形)
// Rectangle与Rectangle的原生方法(无需math-extras)
const other = new Rectangle(50, 50, 100, 100);
rect.containsRect(other); // 如果`other`完全在`rect`内则返回true
rect.intersects(other); // 布尔值:它们是否有重叠?
rect.intersects(other, matrix); // 对`other`应用变换后是否重叠?
// 描边命中测试(alignment: 1 = 内侧,0.5 = 居中,0 = 外侧)
rect.strokeContains(0, 50, 4); // 如果(0,50)位于4px居中描边上则返回true
const circle = new Circle(100, 100, 50);
circle.strokeContains(150, 100, 4, 1); // 内侧对齐描边检测
// getBounds适用于所有形状(返回Rectangle,可接受out参数)
const bounds = circle.getBounds();
const reused = new Rectangle();
new Polygon([0, 0, 100, 0, 50, 100]).getBounds(reused);
// 用作交互的命中区域
const button = new Container();
button.hitArea = new Rectangle(0, 0, 200, 50);
button.eventMode = "static";
button.on("pointerdown", () => {
/* 点击触发 */
});不要混淆原生的(返回)和math-extras中的(返回描述重叠区域的)。
Rectangle.intersects(other)booleanintersection(other)RectangleRectangle layout helpers
Rectangle布局助手
Rectangle ships with mutating helpers used heavily in UI/layout, bounds aggregation, and pixel snapping. All return for chaining.
thists
import { Rectangle } from "pixi.js";
const r = new Rectangle(10, 10, 100, 50);
r.pad(5); // grow on all sides: x=5, y=5, w=110, h=60
r.pad(10, 4); // separate horizontal/vertical padding
r.scale(2); // multiply x, y, width, height by 2
// fit shrinks `this` to lie inside another rect (clipping)
const viewport = new Rectangle(0, 0, 200, 200);
new Rectangle(150, 150, 200, 200).fit(viewport); // -> 150, 150, 50, 50
// enlarge expands `this` to include another rect (bounds aggregation)
const total = new Rectangle();
items.forEach((item) =>
total.enlarge(new Rectangle().copyFromBounds(item.getBounds())),
);
// ceil snaps to a pixel grid (resolution: 1 = whole pixels, 2 = half pixels)
new Rectangle(10.2, 10.6, 100.8, 100.4).ceil();
// copy a Container/Mesh bounds object straight into a Rectangle
new Rectangle().copyFromBounds(container.getBounds());Rectangle内置了用于UI/布局、边界聚合和像素对齐的可变助手方法。所有方法都返回以支持链式调用。
thists
import { Rectangle } from "pixi.js";
const r = new Rectangle(10, 10, 100, 50);
r.pad(5); // 向所有方向扩展:x=5, y=5, w=110, h=60
r.pad(10, 4); // 分别设置水平/垂直内边距
r.scale(2); // 将x、y、width、height乘以2
// fit方法将当前矩形缩小到另一个矩形内部(裁剪)
const viewport = new Rectangle(0, 0, 200, 200);
new Rectangle(150, 150, 200, 200).fit(viewport); // -> 150, 150, 50, 50
// enlarge方法扩展当前矩形以包含另一个矩形(边界聚合)
const total = new Rectangle();
items.forEach((item) =>
total.enlarge(new Rectangle().copyFromBounds(item.getBounds())),
);
// ceil方法将矩形对齐到像素网格(分辨率:1 = 整像素,2 = 半像素)
new Rectangle(10.2, 10.6, 100.8, 100.4).ceil();
// 将Container/Mesh的边界对象直接复制到Rectangle中
new Rectangle().copyFromBounds(container.getBounds());Polygon
Polygon
Polygon accepts four constructor formats: a flat number array, an array of point-like objects, or either passed as spread arguments.
ts
import { Polygon, Point } from "pixi.js";
new Polygon([0, 0, 100, 0, 50, 100]); // flat numbers
new Polygon([new Point(0, 0), new Point(100, 0), new Point(50, 100)]); // PointData[]
new Polygon(0, 0, 100, 0, 50, 100); // spread numbers
new Polygon(new Point(0, 0), new Point(100, 0), new Point(50, 100)); // spread points
const poly = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
poly.points; // [0, 0, 100, 0, 100, 100, 0, 100] (mutable flat array)
poly.closePath; // true by default; false produces an open path
poly.startX; // 0 - first vertex
poly.lastX; // 0 - last vertex (lastY for y)
poly.isClockwise(); // shoelace winding test (useful for SVG hole detection)
// Polygon-in-polygon containment for hole detection
const outer = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
const hole = new Polygon([25, 25, 75, 25, 75, 75, 25, 75]);
outer.containsPolygon(hole); // truePolygon支持四种构造格式:扁平数字数组、Point-like对象数组,或者将以上两种类型作为展开参数传入。
ts
import { Polygon, Point } from "pixi.js";
new Polygon([0, 0, 100, 0, 50, 100]); // 扁平数字
new Polygon([new Point(0, 0), new Point(100, 0), new Point(50, 100)]); // PointData数组
new Polygon(0, 0, 100, 0, 50, 100); // 展开的数字
new Polygon(new Point(0, 0), new Point(100, 0), new Point(50, 100)); // 展开的Point对象
const poly = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
poly.points; // [0, 0, 100, 0, 100, 100, 0, 100](可变扁平数组)
poly.closePath; // 默认true;设为false则生成开放路径
poly.startX; // 0 - 第一个顶点
poly.lastX; // 0 - 最后一个顶点(lastY对应y值)
poly.isClockwise(); // 鞋带式环绕方向检测(对SVG孔洞检测很有用)
// 多边形包含检测,用于孔洞识别
const outer = new Polygon([0, 0, 100, 0, 100, 100, 0, 100]);
const hole = new Polygon([25, 25, 75, 25, 75, 75, 25, 75]);
outer.containsPolygon(hole); // trueConstants
常量
ts
import { DEG_TO_RAD, RAD_TO_DEG, PI_2 } from "pixi.js";
const angle = 45 * DEG_TO_RAD; // 0.785...
const degrees = angle * RAD_TO_DEG; // 45
const fullCircle = PI_2; // Math.PI * 2ts
import { DEG_TO_RAD, RAD_TO_DEG, PI_2 } from "pixi.js";
const angle = 45 * DEG_TO_RAD; // 0.785...
const degrees = angle * RAD_TO_DEG; // 45
const fullCircle = PI_2; // Math.PI * 2Types
类型
- - minimal
PointDatainterface accepted by most APIs. Use it when typing parameters that only need to read coordinates.{x, y} - - extends
PointLikewithPointData,set(),copyFrom(),copyTo(). Implemented by bothequals()andPoint.ObservablePoint - -
Sizeinterface used by renderer/canvas APIs.{ width, height } - - string literal union:
SHAPE_PRIMITIVE. Every shape exposes'rectangle' | 'circle' | 'ellipse' | 'polygon' | 'roundedRectangle' | 'triangle'so you can branch withouttype.instanceof
ts
import type { PointData } from "pixi.js";
function distance(a: PointData, b: PointData): number {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}- - 大多数API接受的最小
PointData接口。当你只需要读取坐标的参数类型时使用它。{x, y} - - 扩展
PointLike,添加了PointData、set()、copyFrom()、copyTo()方法。由equals()和Point实现。ObservablePoint - -
Size接口,用于渲染器/画布API。{ width, height } - - 字符串字面量联合类型:
SHAPE_PRIMITIVE。每个形状都暴露'rectangle' | 'circle' | 'ellipse' | 'polygon' | 'roundedRectangle' | 'triangle'属性,让你无需使用type即可分支处理。instanceof
ts
import type { PointData } from "pixi.js";
function distance(a: PointData, b: PointData): number {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}math-extras (side-effect import)
math-extras(副作用导入)
import 'pixi.js/math-extras'ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";import 'pixi.js/math-extras'ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";Point / ObservablePoint vector methods
Point / ObservablePoint向量方法
All methods accept an optional parameter to avoid allocations. Without , a new Point is returned.
outoutts
const a = new Point(3, 4);
const b = new Point(1, 2);
// Arithmetic
const sum = a.add(b); // Point(4, 6)
const diff = a.subtract(b); // Point(2, 2)
const prod = a.multiply(b); // Point(3, 8) - component-wise
const scaled = a.multiplyScalar(2); // Point(6, 8)
// Dot and cross product
const dot = a.dot(b); // 11
const cross = a.cross(b); // 2 (z-component of 3D cross)
// Length
const len = a.magnitude(); // 5
const lenSq = a.magnitudeSquared(); // 25 (faster for comparisons)
// Normalize to unit vector
const unit = a.normalize(); // Point(0.6, 0.8)
// Projection and reflection
const proj = a.project(b); // project a onto b
const refl = a.reflect(new Point(0, 1)); // reflect across normal
// Rotation
const rotated = a.rotate(Math.PI / 2); // rotate 90 degrees
// Reuse existing point to avoid allocation
const out = new Point();
a.add(b, out); // result written to out所有方法都接受可选的参数以避免内存分配。如果不传入,会返回一个新的Point。
outoutts
const a = new Point(3, 4);
const b = new Point(1, 2);
// 算术运算
const sum = a.add(b); // Point(4, 6)
const diff = a.subtract(b); // Point(2, 2)
const prod = a.multiply(b); // Point(3, 8) - 分量级乘法
const scaled = a.multiplyScalar(2); // Point(6, 8)
// 点积和叉积
const dot = a.dot(b); // 11
const cross = a.cross(b); // 2(3D叉积的z分量)
// 长度
const len = a.magnitude(); // 5
const lenSq = a.magnitudeSquared(); // 25(比较时更快)
// 归一化为单位向量
const unit = a.normalize(); // Point(0.6, 0.8)
// 投影和反射
const proj = a.project(b); // 将a投影到b上
const refl = a.reflect(new Point(0, 1)); // 沿法线反射
// 旋转
const rotated = a.rotate(Math.PI / 2); // 旋转90度
// 复用已有Point以避免分配
const out = new Point();
a.add(b, out); // 结果写入outRectangle extended methods
Rectangle扩展方法
containsRectintersectsRectangleequalsintersectionunionts
import "pixi.js/math-extras";
import { Rectangle } from "pixi.js";
const r1 = new Rectangle(0, 0, 100, 100);
const r2 = new Rectangle(50, 50, 100, 100);
r1.equals(r2); // false
const overlap = r1.intersection(r2); // Rectangle(50, 50, 50, 50)
const envelope = r1.union(r2); // Rectangle(0, 0, 150, 150)
// Optional out parameter
const out = new Rectangle();
r1.intersection(r2, out);containsRectintersectsequalsintersectionunionts
import "pixi.js/math-extras";
import { Rectangle } from "pixi.js";
const r1 = new Rectangle(0, 0, 100, 100);
const r2 = new Rectangle(50, 50, 100, 100);
r1.equals(r2); // false
const overlap = r1.intersection(r2); // Rectangle(50, 50, 50, 50)
const envelope = r1.union(r2); // Rectangle(0, 0, 150, 150)
// 可选的out参数
const out = new Rectangle();
r1.intersection(r2, out);Geometry utility functions
几何工具函数
These functions are exported from , not the main entry.
pixi.js/math-extraspixi.jsts
import {
floatEqual,
lineIntersection,
segmentIntersection,
} from "pixi.js/math-extras";
import { Point } from "pixi.js";
// Epsilon-based float comparison (default epsilon: Number.EPSILON)
floatEqual(0.1 + 0.2, 0.3, 1e-10); // true with reasonable epsilon
floatEqual(1.0, 1.001, 0.01); // true (custom epsilon)
// Unbounded line intersection (returns {x: NaN, y: NaN} if parallel)
const hit = lineIntersection(
new Point(0, 0),
new Point(10, 10), // line A
new Point(10, 0),
new Point(0, 10), // line B
); // Point(5, 5)
if (isNaN(hit.x)) {
/* lines are parallel */
}
// Bounded segment intersection (returns {x: NaN, y: NaN} if segments don't cross)
const segHit = segmentIntersection(
new Point(0, 0),
new Point(10, 10),
new Point(10, 0),
new Point(0, 10),
); // Point(5, 5)
if (isNaN(segHit.x)) {
/* segments don't intersect */
}这些函数从导出,而非主入口。
pixi.js/math-extraspixi.jsts
import {
floatEqual,
lineIntersection,
segmentIntersection,
} from "pixi.js/math-extras";
import { Point } from "pixi.js";
// 基于epsilon的浮点数比较(默认epsilon: Number.EPSILON)
floatEqual(0.1 + 0.2, 0.3, 1e-10); // 使用合理的epsilon时返回true
floatEqual(1.0, 1.001, 0.01); // true(自定义epsilon)
// 无边界直线相交(如果平行则返回{x: NaN, y: NaN})
const hit = lineIntersection(
new Point(0, 0),
new Point(10, 10), // 直线A
new Point(10, 0),
new Point(0, 10), // 直线B
); // Point(5, 5)
if (isNaN(hit.x)) {
/* 直线平行 */
}
// 有边界线段相交(如果线段不交叉则返回{x: NaN, y: NaN})
const segHit = segmentIntersection(
new Point(0, 0),
new Point(10, 10),
new Point(10, 0),
new Point(0, 10),
); // Point(5, 5)
if (isNaN(segHit.x)) {
/* 线段不相交 */
}Common Mistakes
常见错误
HIGH: Importing from @pixi/math
严重错误:从@pixi/math导入
Wrong:
ts
import { Point } from "@pixi/math";Correct:
ts
import { Point } from "pixi.js";v8 uses a single package. All sub-packages like , , etc. were removed.
pixi.js@pixi/math@pixi/core错误写法:
ts
import { Point } from "@pixi/math";正确写法:
ts
import { Point } from "pixi.js";v8使用单一的包。所有子包如、等已被移除。
pixi.js@pixi/math@pixi/coreMEDIUM: Mutating ObservablePoint without triggering observer
中等错误:修改ObservablePoint但未触发观察者
Wrong:
ts
// Replacing the reference loses observation
let pos = container.position;
pos = new Point(100, 200); // container.position unchangedCorrect:
ts
// Mutate in place to trigger the observer
container.position.set(100, 200);
// or
container.position.x = 100;
container.position.y = 200;
// or copy from another point
container.position.copyFrom(new Point(100, 200));Container's position, scale, pivot, origin, and skew are ObservablePoints. Setting or on them triggers the container's transform update. Reassigning the variable reference does not modify the container. Always mutate the existing ObservablePoint via , , or direct property assignment on the original object.
.x.y.set().copyFrom()错误写法:
ts
// 替换引用会丢失观察
let pos = container.position;
pos = new Point(100, 200); // container.position未改变正确写法:
ts
// 原地修改以触发观察者
container.position.set(100, 200);
// 或者
container.position.x = 100;
container.position.y = 200;
// 或者从另一个点复制
container.position.copyFrom(new Point(100, 200));Container的position、scale、pivot、origin和skew都是ObservablePoint。修改它们的.x或.y属性会触发容器的变换更新。重新分配变量引用不会修改容器。始终通过、或直接修改原始对象的属性来变更现有的ObservablePoint。
.set().copyFrom()MEDIUM: Not importing math-extras for extended methods
中等错误:未导入math-extras以使用扩展方法
Wrong:
ts
import { Point } from "pixi.js";
const p = new Point(1, 2);
p.add(new Point(3, 4)); // TypeError: p.add is not a functionCorrect:
ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";
const p = new Point(1, 2);
const sum = p.add(new Point(3, 4)); // worksExtended math utilities (add, subtract, multiply, magnitude, normalize, dot, cross, etc. on Point; intersection methods on shapes) require an explicit . These are not included in the default bundle.
import 'pixi.js/math-extras'错误写法:
ts
import { Point } from "pixi.js";
const p = new Point(1, 2);
p.add(new Point(3, 4)); // TypeError: p.add is not a function正确写法:
ts
import "pixi.js/math-extras";
import { Point } from "pixi.js";
const p = new Point(1, 2);
const sum = p.add(new Point(3, 4)); // 正常工作扩展的数学工具(Point的add、subtract、multiply、magnitude、normalize、dot、cross等方法;形状的相交方法)需要显式导入。这些方法不包含在默认包中。
import 'pixi.js/math-extras'MEDIUM: Storing references to shared/temporary objects
中等错误:存储共享/临时对象的引用
Wrong:
ts
const myPoint = Point.shared;
myPoint.set(100, 200);
// ... later ...
console.log(myPoint.x); // 0 (reset on next access)Correct:
ts
const myPoint = new Point();
myPoint.copyFrom(Point.shared.set(100, 200));
// or just
const myPoint = new Point(100, 200);Point.sharedMatrix.shared错误写法:
ts
const myPoint = Point.shared;
myPoint.set(100, 200);
// ... 稍后 ...
console.log(myPoint.x); // 0(下次访问时已重置)正确写法:
ts
const myPoint = new Point();
myPoint.copyFrom(Point.shared.set(100, 200));
// 或者直接
const myPoint = new Point(100, 200);Point.sharedMatrix.shared