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(camera): a level's edge belongs at the edge of the screen

esenginefbb676a51d95
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 998dfd684..8dae41f64 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -12,6 +12,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
BoxCollider: 'reference/components/physics/#boxcollider',
CacheAsBitmap: 'reference/components/graphics/#cacheasbitmap',
Camera: 'reference/components/graphics/#camera',
+ CameraBounds: 'reference/components/graphics/#camerabounds',
Canvas: 'reference/components/graphics/#canvas',
CapsuleCollider: 'reference/components/physics/#capsulecollider',
ChainCollider: 'reference/components/physics/#chaincollider',
diff --git a/docs/astro/src/content/docs/graphics/camera.mdx b/docs/astro/src/content/docs/graphics/camera.mdx
index 1e53a6ab3..074186ba7 100644
--- a/docs/astro/src/content/docs/graphics/camera.mdx
+++ b/docs/astro/src/content/docs/graphics/camera.mdx
@@ -140,6 +140,36 @@ the camera's `Transform` directly (so the director blends already-followed views
and runs in **play mode only** — the editor's navigation view is never dragged
around by it.
+## Keep the camera inside the level
+
+Add a `CameraBounds` to the camera and the view never leaves the rectangle — the
+level's edge stays at the edge of the screen instead of showing the void past it:
+
+```typescript
+import { Camera, CameraBounds } from 'esengine';
+
+cmds.entity(cameraEntity).insert(CameraBounds, {
+ minX: -1280, maxX: 1280, // the level's world rectangle
+ minY: -768, maxY: 768,
+});
+```
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `minX` / `maxX` | number | `0` | Horizontal interval the view stays inside. |
+| `minY` / `maxY` | number | `0` | Vertical interval the view stays inside. |
+
+Each axis opts in by naming a real interval, so an axis left at `0`/`0` (or any
+`max ≤ min`) is unconstrained — bound the horizontal one alone for a level that
+scrolls sideways forever. When an interval is narrower than the view, the whole
+of it is shown centred rather than pinned against one wall.
+
+The clamp runs after everything that moves a camera, `FollowTarget` included: it
+constrains where a camera ends its frame, not what put it there. Orthographic
+cameras only — a perspective camera's half extents depend on how far away the
+subject is, which no camera property describes. Like the follow, it runs in
+**play mode only**.
+
## Screen ↔ world coordinates
Read the `CameraView` resource to convert between the two spaces — for placing
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/camera.mdx b/docs/astro/src/content/docs/zh-cn/graphics/camera.mdx
index 4043f3025..acdfd8282 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/camera.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/camera.mdx
@@ -128,6 +128,33 @@ const follow = defineSystem([Query(Camera), Commands()], (cameras, cmds) => {
数据形状导出为 `FollowTargetData` 类型。跟随系统直接写相机的 `Transform`(所以 director
混合的是已跟随的视图),且**只在 play 模式运行**——编辑器的导航视图永远不会被它拖走。
+## 把相机限制在关卡内
+
+给相机加一个 `CameraBounds`,视野就再也不会离开这个矩形——关卡的边缘停在屏幕边缘,
+而不是露出外面的虚空:
+
+```typescript
+import { Camera, CameraBounds } from 'esengine';
+
+cmds.entity(cameraEntity).insert(CameraBounds, {
+ minX: -1280, maxX: 1280, // 关卡的世界矩形
+ minY: -768, maxY: 768,
+});
+```
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `minX` / `maxX` | number | `0` | 视野保持在其中的水平区间。 |
+| `minY` / `maxY` | number | `0` | 视野保持在其中的垂直区间。 |
+
+每个轴通过给出一个真实区间来启用,所以留在 `0`/`0`(或任何 `max ≤ min`)的轴不受约束——
+一个横向无限滚动的关卡只约束水平轴即可。当区间比视野还窄时,整个区间会居中显示,
+而不是贴住某一面墙。
+
+这个钳制跑在所有移动相机的东西之后,包括 `FollowTarget`:它约束的是相机结束这一帧时在
+哪里,而不是谁把它放到那里的。只对正交相机生效——透视相机的半尺寸取决于被拍摄物有多远,
+没有任何相机属性描述它。和跟随一样,**只在 play 模式运行**。
+
## 屏幕 ↔ 世界坐标
读 `CameraView` 资源在两个空间之间转换——用于把实体放到光标下,或检测什么可见。无活动相机
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 4408da8b1..2c4af884b 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -68,6 +68,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
CacheAsBitmap: { category: 'graphics', summary: 'Renders an expensive subtree once into a texture and reuses it until marked dirty.', doc: 'graphics/sprites', anchor: 'cache-as-bitmap', anchorZh: '位图缓存cache-as-bitmap' },
Camera: { category: 'graphics', summary: 'A view onto the world — projection, zoom, viewport rect, clear flags and render priority.', doc: 'graphics/camera', anchor: 'the-camera-component', anchorZh: 'camera-组件' },
FollowTarget: { category: 'graphics', summary: 'Makes a camera chase an entity, with an offset, a dead zone and eased catch-up.', doc: 'graphics/camera', anchor: 'follow-a-target', anchorZh: '跟随目标' },
+ CameraBounds: { category: 'graphics', summary: 'The world rectangle a camera may not look outside of, so the level edge stays at the screen edge.', doc: 'graphics/camera', anchor: 'keep-the-camera-inside-the-level', anchorZh: '把相机限制在关卡内' },
Canvas: { category: 'graphics', summary: 'The design resolution and scale mode a scene is authored against — one per scene root.', doc: 'core-concepts/screen', anchor: 'the-canvas-component', anchorZh: 'canvas-组件' },
Light2D: { category: 'graphics', summary: 'A 2D light — point, directional, spot or ambient — that lit renderers and Lit2D materials receive.', doc: 'graphics/lighting', anchor: 'light-types', anchorZh: '光源类型' },
ShadowCaster2D: { category: 'graphics', summary: 'Marks a renderer as an occluder, so 2D lights cast shadows from its silhouette.', doc: 'graphics/lighting', anchor: 'casting-shadows', anchorZh: '投射阴影' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 15dad7d2a..daed2ff21 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -380,6 +380,38 @@
"orthoSize"
]
},
+ {
+ "name": "CameraBounds",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "minX",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "minY",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "maxX",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "maxY",
+ "type": "number",
+ "default": "0"
+ }
+ ],
+ "animatable": [
+ "minX",
+ "minY",
+ "maxX",
+ "maxY"
+ ]
+ },
{
"name": "Canvas",
"source": "cpp",
diff --git a/examples/celestial-heights/assets/scenes/main.esscene b/examples/celestial-heights/assets/scenes/main.esscene
index 3245a1b8e..fa04ee322 100644
--- a/examples/celestial-heights/assets/scenes/main.esscene
+++ b/examples/celestial-heights/assets/scenes/main.esscene
@@ -41,6 +41,15 @@
"deadzone": 40,
"damping": 0.18
}
+ },
+ {
+ "type": "CameraBounds",
+ "data": {
+ "minX": -1280,
+ "minY": -768,
+ "maxX": 1280,
+ "maxY": 768
+ }
}
]
},
diff --git a/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene b/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
index f82e2d9a4..95d1a048c 100644
--- a/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
+++ b/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
@@ -41,6 +41,15 @@
"deadzone": 40,
"damping": 0.18
}
+ },
+ {
+ "type": "CameraBounds",
+ "data": {
+ "minX": -1024,
+ "minY": -640,
+ "maxX": 1024,
+ "maxY": 640
+ }
}
]
},
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 36efca25f..13b5d488a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1481 stable · 17 beta · 1 deprecated
+Symbols: 1483 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1353,6 +1353,19 @@ width: number
BuiltinComponentDef<CameraData>
```
+## CameraBounds — const
+```
+ComponentDef<CameraBoundsData>
+```
+
+## CameraBoundsData — interface
+```
+maxX: number
+maxY: number
+minX: number
+minY: number
+```
+
## CameraData — interface
```
aspectRatio: number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5ded1f28f..1f5b56406 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1500 stable · 22 beta · 1 deprecated
+Symbols: 1502 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1353,6 +1353,19 @@ width: number
BuiltinComponentDef<CameraData>
```
+## CameraBounds — const
+```
+ComponentDef<CameraBoundsData>
+```
+
+## CameraBoundsData — interface
+```
+maxX: number
+maxY: number
+minX: number
+minY: number
+```
+
## CameraData — interface
```
aspectRatio: number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 6d99e9bc4..7e5d50dc8 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1480 stable · 19 beta · 1 deprecated
+Symbols: 1482 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1348,6 +1348,19 @@ width: number
BuiltinComponentDef<CameraData>
```
+## CameraBounds — const
+```
+ComponentDef<CameraBoundsData>
+```
+
+## CameraBoundsData — interface
+```
+maxX: number
+maxY: number
+minX: number
+minY: number
+```
+
## CameraData — interface
```
aspectRatio: number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index b2c3ebd3b..6ffa5239c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1501 stable · 17 beta · 1 deprecated
+Symbols: 1503 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1348,6 +1348,19 @@ width: number
BuiltinComponentDef<CameraData>
```
+## CameraBounds — const
+```
+ComponentDef<CameraBoundsData>
+```
+
+## CameraBoundsData — interface
+```
+maxX: number
+maxY: number
+minX: number
+minY: number
+```
+
## CameraData — interface
```
aspectRatio: number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 8e4065539..eaeffcd0d 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1491 stable · 17 beta · 1 deprecated
+Symbols: 1493 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1348,6 +1348,19 @@ width: number
BuiltinComponentDef<CameraData>
```
+## CameraBounds — const
+```
+ComponentDef<CameraBoundsData>
+```
+
+## CameraBoundsData — interface
+```
+maxX: number
+maxY: number
+minX: number
+minY: number
+```
+
## CameraData — interface
```
aspectRatio: number
diff --git a/sdk/src/camera/CameraBounds.ts b/sdk/src/camera/CameraBounds.ts
new file mode 100644
index 000000000..cb85a9b9d
--- /dev/null
+++ b/sdk/src/camera/CameraBounds.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file CameraBounds.ts
+ * @brief The world rectangle an orthographic camera may not look outside of —
+ * what keeps a level's edge at the edge of the screen instead of
+ * showing the void beyond it.
+ *
+ * A constraint on where the camera IS, not on what moved it: a followed camera,
+ * a scripted one and a blended one all end their frame inside the same
+ * rectangle, because the clamp runs after they have all had their say. Each
+ * axis is independent and opts in by naming a real interval (max > min), so a
+ * component left at its defaults constrains nothing.
+ */
+import { defineComponent, Transform, Camera, ProjectionType } from '../ecs/component';
+import type { World } from '../ecs/world';
+
+export interface CameraBoundsData {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+export const CameraBounds = defineComponent<CameraBoundsData>('CameraBounds', {
+ minX: 0,
+ minY: 0,
+ maxX: 0,
+ maxY: 0,
+});
+
+/**
+ * Where the camera's centre may sit on one axis. Pure: the view's half extent is
+ * held inside [min, max], and when the interval is narrower than the view there
+ * is no such position — the whole of it is shown centred, which reads as a level
+ * too small to scroll rather than as a camera stuck against one wall.
+ */
+export function clampCameraAxis(
+ centre: number,
+ halfExtent: number,
+ min: number,
+ max: number,
+): number {
+ if (!(max > min)) return centre;
+ if (max - min <= halfExtent * 2) return (min + max) / 2;
+ return Math.min(Math.max(centre, min + halfExtent), max - halfExtent);
+}
+
+/** Hold every bounded camera inside its rectangle (called by the bounds system). */
+export function cameraBoundsUpdate(world: World): void {
+ for (const e of world.getEntitiesWithComponents([CameraBounds, Camera, Transform])) {
+ const camera = world.get(e, Camera);
+ // The half extents of a perspective camera depend on how far away the
+ // thing being framed is, which is not a property of the camera; leaving
+ // it alone beats clamping it against a number that means nothing here.
+ if (camera.projectionType !== ProjectionType.Orthographic) continue;
+ const bounds = world.get(e, CameraBounds);
+ const transform = world.get(e, Transform);
+ const halfHeight = camera.orthoSize;
+ const halfWidth = halfHeight * (camera.aspectRatio > 0 ? camera.aspectRatio : 1);
+ const x = clampCameraAxis(transform.position.x, halfWidth, bounds.minX, bounds.maxX);
+ const y = clampCameraAxis(transform.position.y, halfHeight, bounds.minY, bounds.maxY);
+ if (x === transform.position.x && y === transform.position.y) continue;
+ world.set(e, Transform, {
+ ...transform,
+ position: { ...transform.position, x, y },
+ });
+ }
+}
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 0fe00c129..34398f8ea 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -11,6 +11,7 @@ import { Schedule, defineSystem } from '../ecs/system';
import { Res, Time, type TimeData } from '../ecs/resource';
import { playModeOnly } from '../ecs/env';
import { followUpdate } from './FollowTarget';
+import { cameraBoundsUpdate } from './CameraBounds';
import type { ESEngineModule, CppRegistry } from '../wasm';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
@@ -628,6 +629,14 @@ export function cameraPlugin(
{ name: 'CameraFollowSystem' },
), { runIf: playModeOnly });
+ // Runs last of the camera movers: bounds constrain where a camera
+ // ends its frame, whatever put it there.
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [],
+ () => cameraBoundsUpdate(app.world),
+ { name: 'CameraBoundsSystem' },
+ ), { runIf: playModeOnly });
+
app.addSystemToSchedule(Schedule.First, uiCameraSyncSystem);
app.addSystemToSchedule(Schedule.Last, renderSystem);
},
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 43c8627d0..bd1c74d6d 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -50,6 +50,8 @@ export { installEditorGrid } from './camera/editorGridRenderer';
export { CameraDirector, setViewTarget, shakeCamera, BlendCurve } from './camera/CameraDirector';
export { FollowTarget } from './camera/FollowTarget';
export type { FollowTargetData } from './camera/FollowTarget';
+export { CameraBounds } from './camera/CameraBounds';
+export type { CameraBoundsData } from './camera/CameraBounds';
export type { CameraDirectorState } from './camera/CameraDirector';
export type { CameraPOV } from './camera/CameraPlugin';
export { computeEffectiveOrthoSize, uiLayoutRect, EDITOR_VIEW_ENTITY, EDITOR_UI_ANCHOR } from './camera/uiLayoutRect';
diff --git a/sdk/tests/camera-bounds.test.ts b/sdk/tests/camera-bounds.test.ts
new file mode 100644
index 000000000..d0e4c7102
--- /dev/null
+++ b/sdk/tests/camera-bounds.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Camera bounds — the world rectangle a camera may not look outside of,
+ * and the fact that it constrains where a camera IS rather than what
+ * moved it there.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/ecs/world';
+import { Transform, Camera, ProjectionType } from '../src/ecs/component';
+import { CameraBounds, cameraBoundsUpdate, clampCameraAxis } from '../src/camera/CameraBounds';
+import { FollowTarget, followUpdate } from '../src/camera/FollowTarget';
+import type { Entity } from '../src/types';
+import { createMockModule } from './mocks/wasm';
+
+describe('clampCameraAxis', () => {
+ it('leaves an axis alone when no interval was named', () => {
+ expect(clampCameraAxis(500, 480, 0, 0)).toBe(500);
+ expect(clampCameraAxis(500, 480, 100, 100)).toBe(500);
+ });
+
+ it('holds the view inside the interval', () => {
+ expect(clampCameraAxis(-900, 480, -1000, 1000)).toBe(-520);
+ expect(clampCameraAxis(900, 480, -1000, 1000)).toBe(520);
+ });
+
+ it('leaves a centre that already fits', () => {
+ expect(clampCameraAxis(0, 480, -1000, 1000)).toBe(0);
+ });
+
+ it('centres an interval narrower than the view, rather than pinning a wall', () => {
+ expect(clampCameraAxis(-300, 480, -200, 600)).toBe(200);
+ });
+});
+
+describe('cameraBoundsUpdate', () => {
+ let world: World;
+
+ beforeEach(() => {
+ world = new World();
+ const mod = createMockModule();
+ world.connectCpp(mod.getRegistry(), mod);
+ });
+
+ const spawnCamera = (x: number, y: number, bounds?: Partial<typeof CameraBounds._default>): Entity => {
+ const e = world.spawn('camera');
+ world.insert(e, Transform, { position: { x, y, z: 0 } });
+ world.insert(e, Camera, {
+ projectionType: ProjectionType.Orthographic,
+ orthoSize: 540,
+ aspectRatio: 16 / 9,
+ isActive: true,
+ });
+ if (bounds) world.insert(e, CameraBounds, bounds);
+ return e;
+ };
+
+ const at = (e: Entity): { x: number; y: number } => {
+ const p = world.get(e, Transform).position;
+ return { x: p.x, y: p.y };
+ };
+
+ it('holds a camera inside its rectangle on both axes', () => {
+ const e = spawnCamera(-4000, 3000, { minX: -2000, maxX: 2000, minY: -1200, maxY: 1200 });
+ cameraBoundsUpdate(world);
+ expect(at(e)).toEqual({ x: -2000 + 960, y: 1200 - 540 });
+ });
+
+ it('leaves a camera with no bounds component where it is', () => {
+ const e = spawnCamera(-4000, 3000);
+ cameraBoundsUpdate(world);
+ expect(at(e)).toEqual({ x: -4000, y: 3000 });
+ });
+
+ it('constrains only the axes that named an interval', () => {
+ const e = spawnCamera(-4000, 3000, { minX: -2000, maxX: 2000 });
+ cameraBoundsUpdate(world);
+ expect(at(e)).toEqual({ x: -1040, y: 3000 });
+ });
+
+ // Half extents under perspective depend on how far away the subject is,
+ // which orthoSize does not describe — clamping against it would be a number
+ // that means nothing here.
+ it('leaves a perspective camera alone', () => {
+ const e = world.spawn('camera');
+ world.insert(e, Transform, { position: { x: -4000, y: 0, z: 0 } });
+ world.insert(e, Camera, {
+ projectionType: ProjectionType.Perspective,
+ orthoSize: 540,
+ aspectRatio: 16 / 9,
+ isActive: true,
+ });
+ world.insert(e, CameraBounds, { minX: -2000, maxX: 2000 });
+ cameraBoundsUpdate(world);
+ expect(at(e).x).toBe(-4000);
+ });
+
+ // The whole point of running after everything that moves a camera: follow is
+ // one such thing, not the thing bounds belong to.
+ it('holds a followed camera that was damped past the edge', () => {
+ const player = world.spawn('player');
+ world.insert(player, Transform, { position: { x: -5000, y: 0, z: 0 } });
+ const e = spawnCamera(-4900, 0, { minX: -2000, maxX: 2000 });
+ world.insert(e, FollowTarget, { target: player, offsetX: 0, offsetY: 0, deadzone: 0, damping: 0 });
+
+ followUpdate(world, 1 / 60);
+ expect(at(e).x).toBe(-5000);
+ cameraBoundsUpdate(world);
+ expect(at(e).x).toBe(-1040);
+ });
+});