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.

fix(input): deliver edge input to fixed-timestep systems

yhhd157bf271d5d
diff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdx
index 660705c64..dbff73d2c 100644
--- a/docs/astro/src/content/docs/guides/input.mdx
+++ b/docs/astro/src/content/docs/guides/input.mdx
@@ -57,6 +57,28 @@ const spawnAtCursor = defineSystem(
);
```
+## Fixed timestep (physics)
+
+Systems in the `FixedUpdate` family run at a fixed cadence — zero times on a frame
+shorter than the timestep, several times when catching up. The `*Pressed` /
+`*Released` edges account for this: an edge is delivered to **exactly one** fixed
+step (the first at or after it arrived), so a jump read from a physics character
+controller is never dropped on a fast frame nor fired twice on a slow one — no
+buffering on your side.
+
+```typescript
+// Schedule.FixedPreUpdate — the edge is delivered reliably.
+const jump = defineSystem([Query(Mut(CharacterController)), Res(Input)], (players, input) => {
+ for (const [, cc] of players) {
+ if (cc.isOnFloor && input.isKeyPressed('Space')) cc.velocity.y = JUMP_FORCE;
+ }
+});
+```
+
+<Aside type="note">Held state (`isKeyDown`) is level-triggered and already reads
+correctly from any schedule. Step-accurate edge delivery covers keyboard and mouse
+buttons; gamepad edges are frame-granular.</Aside>
+
## Reference
| Group | Methods |
@@ -71,7 +93,8 @@ Each `*Down` reads held state; `*Pressed` / `*Released` are the this-frame edges
## Best practices
-- **Poll every frame** — edges (`*Pressed` / `*Released`) are only set for one frame.
+- **Poll every frame** — edges (`*Pressed` / `*Released`) last one render frame, or
+ one fixed step inside `FixedUpdate` (see above).
- **Guard world clicks with `isPointerOverUI()`** so clicking a button doesn't also
hit the game world.
- **Use `UICameraInfo` for world coordinates**, not raw `mouseX/Y`, so picking
diff --git a/docs/astro/src/content/docs/zh-cn/guides/input.mdx b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
index 3ee277fab..5e17729e6 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/input.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
@@ -55,6 +55,25 @@ const spawnAtCursor = defineSystem(
);
```
+## 固定步长(物理)
+
+`FixedUpdate` 系列的系统以固定节奏运行——比步长短的帧运行零次,追赶时运行多次。
+`*Pressed` / `*Released` 边沿已考虑这点:一个边沿只会被**恰好一个**固定步(第一个
+在它到达之后的步)消费,所以在物理角色控制器里读的跳跃,不会在快帧里丢失、也不会
+在慢帧里触发两次——你无需自己缓冲。
+
+```typescript
+// Schedule.FixedPreUpdate —— 边沿被可靠地投递。
+const jump = defineSystem([Query(Mut(CharacterController)), Res(Input)], (players, input) => {
+ for (const [, cc] of players) {
+ if (cc.isOnFloor && input.isKeyPressed('Space')) cc.velocity.y = JUMP_FORCE;
+ }
+});
+```
+
+<Aside type="note">按住状态(`isKeyDown`)是电平触发,本就能在任意 schedule 正确读取。
+按步精确的边沿投递覆盖键盘与鼠标按键;手柄边沿是按帧粒度的。</Aside>
+
## 参考
| 分组 | 方法 |
@@ -69,7 +88,8 @@ const spawnAtCursor = defineSystem(
## 最佳实践
-- **每帧轮询**——边沿(`*Pressed` / `*Released`)只在一帧被设置。
+- **每帧轮询**——边沿(`*Pressed` / `*Released`)在渲染帧里持续一帧,在 `FixedUpdate`
+ 里持续一个固定步(见上)。
- **用 `isPointerOverUI()` 守卫世界点击**,点按钮时不要也命中游戏世界。
- **世界坐标用 `UICameraInfo`**,而非裸 `mouseX/Y`,让拾取尊重相机。
- **手柄 `pad` 默认 0**——本地多人传索引。
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 0c40b288d..30c7d304c 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -12,7 +12,7 @@ import { EventRegistry, type EventDef } from './event';
import type { ESEngineModule, CppRegistry } from './wasm';
import type { BridgeConnectOptions } from './ecs/BuiltinBridge';
import { UICameraInfo } from './ui/core/ui-camera-info';
-import { inputPlugin } from './input';
+import { inputPlugin, Input } from './input';
import { assetPlugin } from './asset';
import { prefabsPlugin } from './prefabServer';
import { setWasmErrorHandler } from './wasmError';
@@ -699,6 +699,11 @@ export class App {
this.fixedAccumulator_ += delta;
let fixedSteps = 0;
+ // Fixed steps read the input edge mirrors (which persist across frames
+ // until a step consumes them) so a press on a sub-timestep frame isn't
+ // lost and a catch-up frame doesn't replay it. Null when no input plugin
+ // is installed (headless / bare App).
+ const input = this.resources_.has(Input) ? this.resources_.get(Input) : null;
// Direct performance.now() (not platformNow) so the budget guard needs
// no platform init (unit tests call tick() without it) and degrades to a
// no-op where performance is absent — the maxFixedSteps cap still applies.
@@ -706,9 +711,11 @@ export class App {
const fixedStart = perf ? perf.now() : 0;
while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < this.maxFixedSteps_) {
this.fixedAccumulator_ -= this.fixedTimestep_;
+ input?.beginFixedStep();
await this.runSchedule(Schedule.FixedPreUpdate);
await this.runSchedule(Schedule.FixedUpdate);
await this.runSchedule(Schedule.FixedPostUpdate);
+ input?.endFixedStep();
fixedSteps++;
// Stop catching up once this frame's fixed steps blow the time
// budget — drop the backlog below so we don't spiral.
diff --git a/sdk/src/input.ts b/sdk/src/input.ts
index 7bcda8dff..6bd6324df 100644
--- a/sdk/src/input.ts
+++ b/sdk/src/input.ts
@@ -70,16 +70,32 @@ export class InputState {
touchesStarted = new Map<number, TouchPoint>();
touchesEnded = new Set<number>();
+ // — Fixed-timestep edge mirrors —
+ // The render edges above are cleared once per rendered frame (Schedule.Last),
+ // but FixedUpdate runs a variable number of steps per frame (0 on a frame
+ // shorter than the timestep, 2+ when catching up). Reading a render edge from
+ // a fixed system therefore drops presses on sub-timestep frames and doubles
+ // them on catch-up frames. These mirrors are populated alongside the render
+ // edges but cleared per *step* (see endFixedStep), so a press/release reaches
+ // exactly one fixed step — the first one at or after it arrived. While a fixed
+ // step is running, the keyboard/mouse edge queries read these instead.
+ // (Godot's idle- vs physics-frame `just_pressed` split.)
+ keysPressedFixed = new Set<string>();
+ keysReleasedFixed = new Set<string>();
+ mouseButtonsPressedFixed = new Set<number>();
+ mouseButtonsReleasedFixed = new Set<number>();
+ private fixedContext_ = false;
+
isKeyDown(key: string): boolean {
return this.keysDown.has(key);
}
isKeyPressed(key: string): boolean {
- return this.keysPressed.has(key);
+ return (this.fixedContext_ ? this.keysPressedFixed : this.keysPressed).has(key);
}
isKeyReleased(key: string): boolean {
- return this.keysReleased.has(key);
+ return (this.fixedContext_ ? this.keysReleasedFixed : this.keysReleased).has(key);
}
getMousePosition(): { x: number; y: number } {
@@ -91,11 +107,42 @@ export class InputState {
}
isMouseButtonPressed(button: number): boolean {
- return this.mouseButtonsPressed.has(button);
+ return (this.fixedContext_ ? this.mouseButtonsPressedFixed : this.mouseButtonsPressed).has(button);
}
isMouseButtonReleased(button: number): boolean {
- return this.mouseButtonsReleased.has(button);
+ return (this.fixedContext_ ? this.mouseButtonsReleasedFixed : this.mouseButtonsReleased).has(button);
+ }
+
+ // — Edge intake (called by the platform binding for every raw event) —
+ // Centralised here so the render and fixed mirrors can never drift apart.
+
+ /** Record a key-down. The pressed edge only fires on the transition, so a
+ * browser's auto-repeat keydown for a held key doesn't re-trigger it. */
+ noteKeyDown(code: string): void {
+ if (!this.keysDown.has(code)) {
+ this.keysPressed.add(code);
+ this.keysPressedFixed.add(code);
+ }
+ this.keysDown.add(code);
+ }
+
+ noteKeyUp(code: string): void {
+ this.keysDown.delete(code);
+ this.keysReleased.add(code);
+ this.keysReleasedFixed.add(code);
+ }
+
+ noteMouseDown(button: number): void {
+ this.mouseButtons.add(button);
+ this.mouseButtonsPressed.add(button);
+ this.mouseButtonsPressedFixed.add(button);
+ }
+
+ noteMouseUp(button: number): void {
+ this.mouseButtons.delete(button);
+ this.mouseButtonsReleased.add(button);
+ this.mouseButtonsReleasedFixed.add(button);
}
getScrollDelta(): { x: number; y: number } {
@@ -211,6 +258,24 @@ export class InputState {
this.touchesStarted.clear();
this.touchesEnded.clear();
}
+
+ /** Enter a fixed-timestep step: keyboard/mouse edge queries now read the fixed
+ * mirrors. Called by App before each FixedUpdate step. */
+ beginFixedStep(): void {
+ this.fixedContext_ = true;
+ }
+
+ /** Leave a fixed step: drop the consumed edges (so a later step this frame
+ * doesn't see them again) and restore the render context. Edges that arrived
+ * on a frame with no fixed step are never cleared here, so they survive to the
+ * next frame's first step instead of being lost. */
+ endFixedStep(): void {
+ this.keysPressedFixed.clear();
+ this.keysReleasedFixed.clear();
+ this.mouseButtonsPressedFixed.clear();
+ this.mouseButtonsReleasedFixed.clear();
+ this.fixedContext_ = false;
+ }
}
export const Input = defineResource<InputState>(new InputState(), 'Input');
@@ -231,15 +296,11 @@ export class InputPlugin implements Plugin {
getPlatform().bindInputEvents({
onKeyDown(code) {
if (inputRouter.dispatchKeyDown(code)) return;
- if (!state.keysDown.has(code)) {
- state.keysPressed.add(code);
- }
- state.keysDown.add(code);
+ state.noteKeyDown(code);
},
onKeyUp(code) {
if (inputRouter.dispatchKeyUp(code)) return;
- state.keysDown.delete(code);
- state.keysReleased.add(code);
+ state.noteKeyUp(code);
},
onPointerMove(x, y) {
// Pointer position tracks the cursor even when consumed so
@@ -254,13 +315,11 @@ export class InputPlugin implements Plugin {
state.mouseX = x;
state.mouseY = y;
if (inputRouter.dispatchPointerDown(button, x, y)) return;
- state.mouseButtons.add(button);
- state.mouseButtonsPressed.add(button);
+ state.noteMouseDown(button);
},
onPointerUp(button) {
if (inputRouter.dispatchPointerUp(button)) return;
- state.mouseButtons.delete(button);
- state.mouseButtonsReleased.add(button);
+ state.noteMouseUp(button);
},
onWheel(deltaX, deltaY) {
if (inputRouter.dispatchWheel(deltaX, deltaY)) return;
diff --git a/sdk/tests/input-fixed-step.test.ts b/sdk/tests/input-fixed-step.test.ts
new file mode 100644
index 000000000..a09e431b8
--- /dev/null
+++ b/sdk/tests/input-fixed-step.test.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { App } from '../src/app';
+import { Schedule, defineSystem } from '../src/system';
+import { Res } from '../src/resource';
+import { Input, InputState } from '../src/input';
+
+/**
+ * Edge input (isKeyPressed / isMouseButtonPressed) read from a FixedUpdate-family
+ * schedule must reach exactly one fixed step — the render-frame edge lifecycle
+ * (cleared in Schedule.Last) otherwise drops presses on sub-timestep frames and
+ * replays them on catch-up frames. See InputState fixed-edge mirrors.
+ */
+describe('input edges in fixed timestep', () => {
+ // fixedTimestep defaults to 1/60. tick(1/120) advances the accumulator by half
+ // a step, so two of them equal one step — lets us build sub-timestep frames.
+ const HALF = 1 / 120;
+ const STEP = 1 / 60;
+
+ function harness() {
+ const app = App.new();
+ const input = new InputState();
+ app.insertResource(Input, input);
+
+ let fixedPressed = 0;
+ let updatePressed = 0;
+ let fixedHeld = 0;
+
+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
+ [Res(Input)],
+ (i: InputState) => {
+ if (i.isKeyPressed('Space')) fixedPressed++;
+ if (i.isKeyDown('KeyD')) fixedHeld++;
+ },
+ { name: 'FixedRead' },
+ ));
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Input)],
+ (i: InputState) => { if (i.isKeyPressed('Space')) updatePressed++; },
+ { name: 'UpdateRead' },
+ ));
+ // Mirrors InputPlugin's InputClearSystem (clears render edges each frame).
+ app.addSystemToSchedule(Schedule.Last, defineSystem(
+ [Res(Input)],
+ (i: InputState) => { i.clearFrameState(); },
+ { name: 'ClearRender' },
+ ));
+
+ return {
+ app, input,
+ counts: () => ({ fixedPressed, updatePressed, fixedHeld }),
+ };
+ }
+
+ it('delivers a press from a sub-timestep frame to the next fixed step, once', async () => {
+ const h = harness();
+
+ // Frame 1: the press arrives on a frame too short to run a fixed step.
+ h.input.noteKeyDown('Space');
+ await h.app.tick(HALF);
+ expect(h.counts().fixedPressed).toBe(0); // no fixed step ran this frame
+
+ // Frame 2: accumulator now reaches one step, which consumes the buffered press.
+ await h.app.tick(HALF);
+ expect(h.counts().fixedPressed).toBe(1);
+
+ // Later steps must not replay it.
+ await h.app.tick(STEP);
+ await h.app.tick(STEP);
+ expect(h.counts().fixedPressed).toBe(1);
+ });
+
+ it('delivers a press only once even when a frame runs multiple fixed steps', async () => {
+ const h = harness();
+
+ h.input.noteKeyDown('Space');
+ // A long frame: two steps' worth of accumulator in one tick.
+ await h.app.tick(2 * STEP);
+ expect(h.counts().fixedPressed).toBe(1);
+ });
+
+ it('still delivers the press to render-context systems once per frame', async () => {
+ const h = harness();
+
+ h.input.noteKeyDown('Space');
+ await h.app.tick(STEP);
+ expect(h.counts().updatePressed).toBe(1);
+
+ // Edge is gone next frame (render edge cleared in Last).
+ await h.app.tick(STEP);
+ expect(h.counts().updatePressed).toBe(1);
+ });
+
+ it('reads held keys in fixed context every step, regardless of frame timing', async () => {
+ const h = harness();
+
+ h.input.noteKeyDown('KeyD'); // held down
+ await h.app.tick(STEP); // 1 step
+ await h.app.tick(2 * STEP); // 2 steps
+ expect(h.counts().fixedHeld).toBe(3);
+
+ h.input.noteKeyUp('KeyD');
+ await h.app.tick(STEP);
+ expect(h.counts().fixedHeld).toBe(3);
+ });
+});