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(engine): camera shake — director modifier layer (camera modernization D1)

esengineadb242b0f3d5
diff --git a/sdk/src/camera/CameraDirector.ts b/sdk/src/camera/CameraDirector.ts
index 23244bcdb..9dbd19f03 100644
--- a/sdk/src/camera/CameraDirector.ts
+++ b/sdk/src/camera/CameraDirector.ts
@@ -69,6 +69,16 @@ function clonePOV(p: CameraPOV): CameraPOV {
return { ...p, viewport: { ...p.viewport } };
}
+/** A transient camera shake — a decaying view-space perturbation (UE modifier). */
+export interface ActiveShake {
+ amplitude: number; // positional, world units
+ rotation: number; // rotational, radians
+ frequency: number; // Hz
+ duration: number; // seconds
+ startTime: number; // seconds; -1 until first applied
+ seed: number; // decorrelates concurrent shakes
+}
+
export interface CameraDirectorState {
/** Committed view-target entity, or -1 → fall back to the active/priority camera. */
target: number;
@@ -85,6 +95,9 @@ export interface CameraDirectorState {
curve: number;
/** Last resolved main POV — also the snapshot source when a new blend starts. */
currentMain: CameraPOV | null;
+ /** Active transient shakes (applied to the rendered POV, never to the Transform). */
+ shakes: ActiveShake[];
+ shakeSeq: number;
}
export const DEFAULT_DIRECTOR: CameraDirectorState = {
@@ -99,8 +112,15 @@ export const DEFAULT_DIRECTOR: CameraDirectorState = {
duration: 0,
curve: BlendCurve.EaseInOut,
currentMain: null,
+ shakes: [],
+ shakeSeq: 0,
};
+/** A fresh director state (own arrays) — use per App, not the shared default. */
+export function createDirectorState(): CameraDirectorState {
+ return { ...DEFAULT_DIRECTOR, from: null, currentMain: null, shakes: [] };
+}
+
export const CameraDirector = defineResource<CameraDirectorState>(
{ ...DEFAULT_DIRECTOR },
'CameraDirector',
@@ -124,6 +144,58 @@ export function setViewTarget(
dir.pendingCurve = opts?.curve ?? BlendCurve.EaseInOut;
}
+/**
+ * Trigger a transient camera shake on the active view — a decaying perturbation
+ * applied to the rendered POV only (never to a camera's Transform, so it always
+ * recovers and never dirties the scene). The UE `StartCameraShake` analog.
+ */
+export function shakeCamera(
+ app: App,
+ opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number },
+): void {
+ const dir = app.getResource(CameraDirector);
+ dir.shakes.push({
+ amplitude: opts?.amplitude ?? 12,
+ rotation: opts?.rotation ?? 0,
+ frequency: opts?.frequency ?? 22,
+ duration: opts?.duration ?? 0.4,
+ startTime: -1,
+ seed: dir.shakeSeq++,
+ });
+}
+
+// Deterministic smooth pseudo-noise in ~[-1, 1] (two decorrelated sines).
+const shakeNoise = (t: number, seed: number): number =>
+ Math.sin(t + seed * 1.3) * 0.6 + Math.sin(t * 1.7 + seed * 2.9) * 0.4;
+
+/**
+ * Apply + age the active shakes, returning the POV offset for rendering. Drops
+ * expired shakes. Mutates the shake list, so it runs only on the advancing
+ * (render) resolve — the peek resolve leaves the view un-shaken (so screen<->world
+ * doesn't jitter while the camera shakes).
+ */
+function applyShakes(dir: CameraDirectorState, pov: CameraPOV, now: number): CameraPOV {
+ if (dir.shakes.length === 0) return pov;
+ let ox = 0;
+ let oy = 0;
+ let orot = 0;
+ const alive: ActiveShake[] = [];
+ for (const s of dir.shakes) {
+ if (s.startTime < 0) s.startTime = now;
+ const e = now - s.startTime;
+ if (e >= s.duration || s.duration <= 0) continue; // expired → dropped
+ const decay = 1 - e / s.duration;
+ const phase = 2 * Math.PI * s.frequency * e;
+ ox += s.amplitude * decay * shakeNoise(phase, s.seed);
+ oy += s.amplitude * decay * shakeNoise(phase, s.seed + 11);
+ orot += s.rotation * decay * shakeNoise(phase, s.seed + 23);
+ alive.push(s);
+ }
+ dir.shakes = alive;
+ if (ox === 0 && oy === 0 && orot === 0) return pov;
+ return { ...pov, x: pov.x + ox, y: pov.y + oy, rotation: pov.rotation + orot };
+}
+
/** The active camera by policy: isActive wins (authoritative), else highest priority. */
function pickActive(candidates: CameraPOV[]): CameraPOV {
const active = candidates.find((c) => c.isActive);
@@ -173,19 +245,22 @@ export function resolveMainPOV(
(dir.target >= 0 ? candidates.find((c) => c.entity === dir.target) : undefined) ??
pickActive(candidates);
+ let main: CameraPOV;
if (dir.blending && dir.from) {
const elapsed = now - dir.startTime;
if (dir.duration <= 0 || elapsed >= dir.duration) {
dir.blending = false;
dir.from = null;
- dir.currentMain = targetPOV;
- return targetPOV;
+ main = targetPOV;
+ } else {
+ main = lerpPOV(dir.from, targetPOV, applyCurve(dir.curve, elapsed / dir.duration));
}
- const blended = lerpPOV(dir.from, targetPOV, applyCurve(dir.curve, elapsed / dir.duration));
- dir.currentMain = blended;
- return blended;
+ } else {
+ main = targetPOV;
}
- dir.currentMain = targetPOV;
- return targetPOV;
+ // currentMain stays the pre-shake view (blend snapshot + screen<->world use it);
+ // shake is a render-only transient offset on top.
+ dir.currentMain = main;
+ return applyShakes(dir, main, now);
}
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 721b10f6d..9016c01a3 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -12,7 +12,7 @@ import type { Entity } from '../types';
import { UICameraInfo } from '../ui/UICameraInfo';
import { ProjectionType, ScaleMode, SceneOwner, ClearFlags } from '../component';
import { EditorView, DEFAULT_EDITOR_VIEW, type EditorViewData } from './EditorView';
-import { CameraDirector, DEFAULT_DIRECTOR, resolveMainPOV } from './CameraDirector';
+import { CameraDirector, createDirectorState, resolveMainPOV } from './CameraDirector';
import { RenderPipeline } from '../renderPipeline';
import { Renderer } from '../renderer';
import { platformNow } from '../platform';
@@ -393,8 +393,9 @@ export function cameraPlugin(
// it; the editor activates it in edit mode (see desktop EngineHost).
app.insertResource(EditorView, { ...DEFAULT_EDITOR_VIEW });
// The camera director: by default it just tracks the active camera;
- // games call setViewTarget(app, entity, {time, curve}) to blend.
- app.insertResource(CameraDirector, { ...DEFAULT_DIRECTOR });
+ // games call setViewTarget(app, entity, {time, curve}) to blend, or
+ // shakeCamera(app, {...}) to shake. Fresh state (own arrays) per App.
+ app.insertResource(CameraDirector, createDirectorState());
const viewport = getViewportSize ?? (() => {
const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index e3517885f..9321bd3a7 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -40,7 +40,7 @@ export { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextur
export { CameraView, CameraViewApi } from './camera/Camera';
export { EditorView, DEFAULT_EDITOR_VIEW } from './camera/EditorView';
export type { EditorViewData } from './camera/EditorView';
-export { CameraDirector, setViewTarget, BlendCurve } from './camera/CameraDirector';
+export { CameraDirector, setViewTarget, shakeCamera, BlendCurve } from './camera/CameraDirector';
export type { CameraDirectorState } from './camera/CameraDirector';
export type { CameraPOV } from './camera/CameraPlugin';
diff --git a/sdk/tests/camera-director.test.ts b/sdk/tests/camera-director.test.ts
index b02e93aa6..c0fe5db3a 100644
--- a/sdk/tests/camera-director.test.ts
+++ b/sdk/tests/camera-director.test.ts
@@ -8,7 +8,7 @@ import {
lerpPOV,
resolveMainPOV,
BlendCurve,
- DEFAULT_DIRECTOR,
+ createDirectorState,
type CameraDirectorState,
} from '../src/camera/CameraDirector';
import type { CameraPOV } from '../src/camera/CameraPlugin';
@@ -32,7 +32,7 @@ const mkPOV = (over: Partial<CameraPOV>): CameraPOV => ({
...over,
});
const dir = (over?: Partial<CameraDirectorState>): CameraDirectorState => ({
- ...DEFAULT_DIRECTOR,
+ ...createDirectorState(),
...over,
});
@@ -109,4 +109,23 @@ describe('resolveMainPOV', () => {
expect(resolveMainPOV(d, [A, B], 5, false)).toBe(A);
expect(d.hasPending).toBe(true); // not consumed
});
+
+ it('shake offsets the rendered POV, decays, then expires (render path only)', () => {
+ const d = dir();
+ d.shakes.push({ amplitude: 50, rotation: 0, frequency: 10, duration: 1, startTime: -1, seed: 0 });
+ resolveMainPOV(d, [A], 0, true); // first advance sets startTime (e=0 → ~no offset)
+ const mid = resolveMainPOV(d, [A], 0.3, true);
+ expect(Math.abs(mid!.x)).toBeGreaterThan(0); // shaken off-center
+ expect(d.shakes.length).toBe(1);
+ const after = resolveMainPOV(d, [A], 1.2, true); // past duration
+ expect(after!.x).toBeCloseTo(0);
+ expect(d.shakes.length).toBe(0); // expired + dropped
+ });
+
+ it('peek does not age or drop shakes', () => {
+ const d = dir({ currentMain: A });
+ d.shakes.push({ amplitude: 50, rotation: 0, frequency: 10, duration: 1, startTime: -1, seed: 0 });
+ resolveMainPOV(d, [A], 0.3, false); // peek
+ expect(d.shakes.length).toBe(1);
+ });
});