Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(viewport): the pivot is draggable, and dragging it does not move the sprite

yhh80db6c1f2394
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index f121830bf..9ddc9756f 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -265,6 +265,37 @@ export const ViewportController = {
};
},
+ /**
+ * The frame a Sprite's pivot handle drags in (see `pivotDrag`), or null for an entity
+ * with no draggable pivot: a zero world size leaves no fraction to solve for, a UINode
+ * no pivot at all. `client` is the entity origin — the pivot the sprite is drawn
+ * around; `w`/`h` carry the world scale, so the fraction divides by the drawn rect.
+ */
+ spritePivotFrame(id: EntityId): {
+ client: { x: number; y: number };
+ origin: { x: number; y: number };
+ rot: number; w: number; h: number; pivot: { x: number; y: number };
+ } | null {
+ const world = EngineHost.world;
+ if (!world || !world.valid(id) || !world.has(id, Sprite) || !world.has(id, Transform)) return null;
+ if (world.has(id, UINode)) return null;
+ const t = world.get(id, Transform);
+ const sp = world.get(id, Sprite);
+ const w = sp.size.x * t.worldScale.x;
+ const h = sp.size.y * t.worldScale.y;
+ if (!Number.isFinite(w) || !Number.isFinite(h) || w === 0 || h === 0) return null;
+ const client = this.projectorFor(id)(t.worldPosition.x, t.worldPosition.y);
+ if (!client) return null;
+ return {
+ client,
+ origin: { x: t.worldPosition.x, y: t.worldPosition.y },
+ rot: quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number }),
+ w,
+ h,
+ pivot: { x: sp.pivot?.x ?? 0.5, y: sp.pivot?.y ?? 0.5 },
+ };
+ },
+
/** UI entities under the pointer, most specific first; unpickable ones dropped. */
pickUIEntities(clientX: number, clientY: number): EntityId[] {
const world = EngineHost.world;
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index 82dc2f3af..5e74ecfa0 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -69,6 +69,10 @@ export const viewportMessages = defineMessages({
'vp.flag.grid': { en: 'Grid', zh: '网格' },
'vp.flag.gizmos': { en: 'Gizmos', zh: 'Gizmo' },
'vp.flag.colliders': { en: 'Physics', zh: '物理' },
+ 'vp.pivotHandle': {
+ en: 'Drag to move the pivot within the sprite (the sprite stays put)',
+ zh: '拖动以在精灵内部移动轴心(精灵本身不动)',
+ },
'vp.flag.tileCollision': { en: 'Tile Collision', zh: '瓦片碰撞' },
'vp.flag.previewFx': { en: 'Preview FX', zh: '预览特效' },
'vp.flag.perf': { en: 'Perf', zh: '性能' },
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 6f57a53da..966f1f7b5 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -48,7 +48,7 @@ import { usePanelWindow, eventWindow } from '@/components/PanelWindow';
import type { ToolMode, EntityId } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
-import { GIZMO, colliderHandleClass, type GizmoAxis } from '@/tools/gizmo';
+import { GIZMO, colliderHandleClass, pivotDrag, type GizmoAxis } from '@/tools/gizmo';
import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';
import { Marquee } from '@/tools/marquee';
import { TilePaintPreview } from '@/tools/tilePreview';
@@ -139,6 +139,24 @@ function startSizeHandleDrag(
});
}
+// Drag a sprite's pivot handle → Sprite.pivot with the artwork held still (the maths,
+// and why the transform moves too, are in `pivotDrag`). Both writes are absolute in ONE
+// grab-time frame, so a long drag cannot compound; one transaction, one undo step.
+function startPivotHandleDrag(rt: number, e: ReactPointerEvent): void {
+ if (e.button !== 0) return;
+ const src = SceneModel.sourceFor(rt);
+ const f = ViewportController.spritePivotFrame(rt);
+ if (src == null || !f) return;
+ e.stopPropagation();
+ runHandleDrag(eventWindow(e), 'Sprite pivot', (ev) => {
+ const p = ViewportController.canvasToWorld(ev.clientX, ev.clientY);
+ if (!p) return;
+ const next = pivotDrag(f, p);
+ SceneCommands.setField(src, 'Sprite', 'pivot', 'vec2', [next.pivot.x, next.pivot.y]);
+ SceneCommands.setEntityXY(src, next.pos.x, next.pos.y);
+ });
+}
+
// Drag a collider point handle → a Vec2 field (box/circle/capsule offset, segment
// endpoint) or ONE element of a Vec2[] (polygon vertex, chain point). The cursor is
// un-rotated into the entity's local frame and scaled to physics metres (÷ppu), then
@@ -782,6 +800,7 @@ export function Viewport() {
const playHostRef = useRef<HTMLDivElement>(null);
const gizmoRef = useRef<HTMLDivElement>(null);
const uiGizmoRef = useRef<HTMLDivElement>(null);
+ const pivotHandleRef = useRef<HTMLDivElement>(null);
const designSvgRef = useRef<SVGSVGElement>(null);
const designLabelRef = useRef<HTMLDivElement>(null);
// One outline div per selected entity, keyed by source id and positioned by the rAF.
@@ -1146,6 +1165,29 @@ export function Viewport() {
}
}
+ // Sprite pivot handle: the dot a single selected sprite turns about. It sits at
+ // the entity origin, where Move and Scale keep their centre grab — so, like the
+ // collider offset handle, it yields, appearing only under the pointer tool.
+ const pvh = pivotHandleRef.current;
+ if (pvh) {
+ const pid = useSelection.getState().selectedId;
+ const prt = ready && showG && pid != null && SceneModel.isEditable(pid) && selIds.length === 1
+ && useEditorStore.getState().tool === 'select'
+ ? SceneModel.runtimeFor(pid)
+ : undefined;
+ const f = prt != null ? ViewportController.spritePivotFrame(prt) : null;
+ if (f) {
+ pvh.style.transform = `translate(${f.client.x}px, ${f.client.y}px)`;
+ pvh.style.opacity = '1';
+ pvh.style.pointerEvents = 'auto';
+ pvh.dataset.rt = String(prt);
+ } else {
+ pvh.style.opacity = '0';
+ pvh.style.pointerEvents = 'none';
+ delete pvh.dataset.rt;
+ }
+ }
+
// Design-resolution overlay (UI mode): the Canvas' authored design frame, the
// simulated device's visible frame, its letterbox bars, and the safe-area inset,
// all projected from world each frame so they lock to pan/zoom.
@@ -2524,6 +2566,19 @@ export function Viewport() {
))}
{/* The merged selection box (shown only above the threshold; rAF-positioned). */}
<div ref={mergedSelRef} className="viewport__selection" style={{ opacity: 0 }} aria-hidden="true" />
+ {/* The selected sprite's pivot dot. One element for the whole viewport (only a
+ single selection ever gets it); the rAF parks it and stamps the runtime id the
+ drag reads, so no per-entity element is minted for a handle that shows once. */}
+ <div
+ ref={pivotHandleRef}
+ className="viewport__pivot-handle"
+ style={{ opacity: 0, pointerEvents: 'none' }}
+ title={t('vp.pivotHandle')}
+ onPointerDown={(e) => {
+ const rt = e.currentTarget.dataset.rt;
+ if (rt != null) startPivotHandleDrag(Number(rt), e);
+ }}
+ />
<div ref={marqueeRef} className="viewport__marquee" aria-hidden="true" />
<div ref={tileSelRef} className="viewport__tilesel" aria-hidden="true" />
<div ref={tilePreviewRef} className="viewport__tilepreview" aria-hidden="true" />
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 943c13dd3..e2e72e832 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -265,6 +265,27 @@
.viewport__selection.primary {
border-width: 1.5px;
}
+/* The selected sprite's pivot dot: a ring with a centre point, drawn ON the entity
+ origin. `translate` puts its centre there (hence the -50% pair), and it sits above
+ the selection outline it is dragged across. */
+.viewport__pivot-handle {
+ position: absolute;
+ top: -6px;
+ left: -6px;
+ z-index: 2;
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ border: 1.5px solid var(--sel);
+ background: radial-gradient(circle, var(--sel) 0 2px, transparent 2px);
+ box-shadow: 0 0 0 1px rgba(14, 15, 18, 0.7);
+ cursor: move;
+ will-change: transform, opacity;
+}
+.viewport__pivot-handle:hover {
+ background: radial-gradient(circle, var(--sel) 0 3px, rgba(255, 255, 255, 0.25) 3px);
+}
+
/* Nest-target hint while dragging a widget from the palette — the container the
drop would parent into. Accent (UI chrome blue), distinct from the orange
selection outline. */
diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.ts
index 680c3b124..48488b50a 100644
--- a/desktop/src/tools/gizmo.ts
+++ b/desktop/src/tools/gizmo.ts
@@ -117,6 +117,37 @@ export function constrainLocalDelta(axis: GizmoAxis, dx: number, dy: number, ang
return [k * ax, k * ay];
}
+/** What a pivot drag is measured against, snapshotted when the handle is grabbed.
+ * `w`/`h` are the sprite's world size with scale already folded in, so the fraction
+ * divides by the rect that is actually drawn. */
+export interface PivotFrame {
+ origin: Pt;
+ rot: number;
+ w: number;
+ h: number;
+ pivot: Pt;
+}
+
+/**
+ * Where a pivot drag lands: the fraction to store, and the world position that keeps
+ * the artwork still. A sprite is drawn at `position − R·(size·pivot)`, so moving the
+ * pivot alone slides the body off the cursor — instead the transform follows the
+ * cursor and the pivot absorbs the same offset, leaving that expression unchanged.
+ */
+export function pivotDrag(f: PivotFrame, cursor: Pt): { pivot: Pt; pos: Pt } {
+ const cos = Math.cos(f.rot);
+ const sin = Math.sin(f.rot);
+ const dx = cursor.x - f.origin.x;
+ const dy = cursor.y - f.origin.y;
+ return {
+ pivot: {
+ x: f.pivot.x + (dx * cos + dy * sin) / f.w,
+ y: f.pivot.y + (-dx * sin + dy * cos) / f.h,
+ },
+ pos: { x: cursor.x, y: cursor.y },
+ };
+}
+
/** Centroid of a set of world points — the group transform pivot for multi-select. */
export function groupPivot(points: readonly Pt[]): Pt {
if (points.length === 0) return { x: 0, y: 0 };
diff --git a/desktop/tests/gizmo-pivot-drag.test.ts b/desktop/tests/gizmo-pivot-drag.test.ts
new file mode 100644
index 000000000..0e0f5816c
--- /dev/null
+++ b/desktop/tests/gizmo-pivot-drag.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Pivot-handle math: dragging a sprite's pivot must not move the sprite.
+ *
+ * The whole point of the handle is choosing a turning point on art that is already
+ * placed, so every case here asserts the same invariant — the artwork's corner is
+ * where it was — rather than the formula that happens to produce it.
+ */
+import { describe, it, expect } from 'vitest';
+import { pivotDrag, type PivotFrame } from '@/tools/gizmo';
+
+const close = (a: number, b: number, eps = 1e-9) => expect(Math.abs(a - b)).toBeLessThanOrEqual(eps);
+
+/** Where the sprite's local (0,0) corner sits in the world: `pos − R·(size·pivot)`,
+ * the same expression the renderer draws from. */
+function corner(pos: { x: number; y: number }, rot: number, w: number, h: number, pivot: { x: number; y: number }) {
+ const cos = Math.cos(rot), sin = Math.sin(rot);
+ const lx = -w * pivot.x, ly = -h * pivot.y;
+ return { x: pos.x + lx * cos - ly * sin, y: pos.y + lx * sin + ly * cos };
+}
+
+const frame = (over: Partial<PivotFrame> = {}): PivotFrame => ({
+ origin: { x: 0, y: 0 }, rot: 0, w: 200, h: 100, pivot: { x: 0.5, y: 0.5 }, ...over,
+});
+
+describe('pivotDrag', () => {
+ it('is a no-op when the cursor has not left the handle', () => {
+ const f = frame();
+ const r = pivotDrag(f, f.origin);
+ close(r.pivot.x, 0.5); close(r.pivot.y, 0.5);
+ close(r.pos.x, 0); close(r.pos.y, 0);
+ });
+
+ it('reads the cursor as a fraction of the sprite, per axis', () => {
+ // Half a width right and a quarter height up, on a 200×100 sprite.
+ const r = pivotDrag(frame(), { x: 100, y: 25 });
+ close(r.pivot.x, 1);
+ close(r.pivot.y, 0.75);
+ });
+
+ it('leaves the artwork exactly where it was', () => {
+ const f = frame();
+ const before = corner({ x: 0, y: 0 }, f.rot, f.w, f.h, f.pivot);
+ const r = pivotDrag(f, { x: 37, y: -19 });
+ const after = corner(r.pos, f.rot, f.w, f.h, r.pivot);
+ close(after.x, before.x); close(after.y, before.y);
+ });
+
+ it('leaves the artwork where it was under rotation and scale', () => {
+ // w/h carry the world scale, so a scaled sprite is just a bigger denominator.
+ const f = frame({ origin: { x: -40, y: 12 }, rot: Math.PI / 3, w: 200 * 2.5, h: 100 * 0.4 });
+ const before = corner(f.origin, f.rot, f.w, f.h, f.pivot);
+ const r = pivotDrag(f, { x: 128, y: -64 });
+ const after = corner(r.pos, f.rot, f.w, f.h, r.pivot);
+ close(after.x, before.x, 1e-8); close(after.y, before.y, 1e-8);
+ });
+
+ it('measures along the sprite\'s own axes, not the world\'s', () => {
+ // At 90° the sprite's local +X points along world +Y and its local +Y along world
+ // −X. A diagonal drag pins both axes AND both signs — an axis swapped or negated
+ // here looks perfectly correct on every upright sprite.
+ const r = pivotDrag(frame({ rot: Math.PI / 2 }), { x: 50, y: 100 });
+ close(r.pivot.x, 1);
+ close(r.pivot.y, 0);
+ });
+
+ it('lets the pivot leave the sprite, which is a legal hinge', () => {
+ const r = pivotDrag(frame(), { x: -300, y: 0 });
+ close(r.pivot.x, -1);
+ expect(Number.isFinite(r.pivot.x)).toBe(true);
+ });
+});