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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): the Velocity component actually moves things
esenginee32aa4cd8256
diff --git a/docs/astro/src/content/docs/guides/scripting.mdx b/docs/astro/src/content/docs/guides/scripting.mdxindex 4904b9f07..5f3fa3a75 100644--- a/docs/astro/src/content/docs/guides/scripting.mdx+++ b/docs/astro/src/content/docs/guides/scripting.mdx@@ -191,6 +191,28 @@ const arm = defineSystem([Res(TimerRes)], (timers) => {Timers advance in play mode only — in the editor's edit mode they hold, like therest of game time.+## Constant motion: the Velocity component++For "just keep moving" motion — projectiles, drifting debris, spinners — attach the+builtin `Velocity` component instead of writing a movement system. The engine+integrates it into `Transform` every update in play mode:++```typescript+import { Velocity } from 'esengine';++world.spawn()+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, { texture: bulletTex })+ .insert(Velocity, {+ linear: { x: 240, y: 0, z: 0 }, // units per second+ angular: { x: 0, y: 0, z: Math.PI }, // radians per second (z = 2D spin)+ });+```++Entities with a `RigidBody` are skipped — the physics solver owns their transform,+so the two never fight over one entity. `Velocity` is also replication-aware: its+fields are replicated, so networked clients can dead-reckon between snapshots.+## How it fits togetherA behavior is not a special case — it compiles to exactly one `defineComponent` plusdiff --git a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdxindex f8e8fed35..0aa8e4436 100644--- a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx@@ -178,6 +178,26 @@ const arm = defineSystem([Res(TimerRes)], (timers) => {计时器只在播放模式推进——编辑器编辑态下与其余游戏时间一样保持不动。+## 匀速运动:Velocity 组件++对"就是一直动"的运动——子弹、漂移的碎片、旋转体——直接挂内置的 `Velocity` 组件,+不必手写移动系统。引擎在播放模式下每次 update 把它积分进 `Transform`:++```typescript+import { Velocity } from 'esengine';++world.spawn()+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, { texture: bulletTex })+ .insert(Velocity, {+ linear: { x: 240, y: 0, z: 0 }, // 单位/秒+ angular: { x: 0, y: 0, z: Math.PI }, // 弧度/秒(z = 2D 自转)+ });+```++带 `RigidBody` 的实体会被跳过——物理求解器拥有它们的变换,两者永远不会争抢同一个实体。+`Velocity` 也是复制感知的:它的字段参与网络复制,联网客户端可以在快照之间做航位推算。+## 它如何组合一个 behavior 并不是特例——它编译成恰好一个 `defineComponent` 加一个 `defineSystem`。当你的逻辑diff --git a/sdk/src/velocity.ts b/sdk/src/velocity.tsnew file mode 100644index 000000000..bae5547be--- /dev/null+++ b/sdk/src/velocity.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file velocity.ts+ * @brief Velocity concept — integrates the builtin Velocity component into Transform.+ */+import type { Plugin } from './app';+import { defineSystem, Schedule, GetWorld } from './system';+import { Query, Mut } from './query';+import { Res, Time, type TimeData } from './resource';+import { playModeOnly } from './env';+import { Transform, Velocity, getComponentRegistry } from './component';+import type { TransformData, VelocityData } from './component';+import type { Entity } from './types';+import type { World } from './world';++export const velocitySystem = defineSystem(+ [Query(Mut(Transform), Velocity), Res(Time), GetWorld()],+ (+ query: Iterable<[Entity, TransformData, VelocityData]>,+ time: TimeData,+ world: World,+ ) => {+ const dt = time.delta;+ if (dt <= 0) return;+ // Physics-owned bodies get their transform from the solver; integrating+ // Velocity on top would double-move them. RigidBody lives in the physics+ // subpath, so it is resolved by name — absent registry entry means the+ // physics module was never loaded and no entity can carry it.+ const rigidBody = getComponentRegistry().get('RigidBody');+ for (const [entity, transform, velocity] of query) {+ if (rigidBody && world.has(entity, rigidBody)) continue;++ const lin = velocity.linear;+ if (lin.x !== 0 || lin.y !== 0 || lin.z !== 0) {+ const p = transform.position;+ transform.position = {+ x: p.x + lin.x * dt,+ y: p.y + lin.y * dt,+ z: p.z + lin.z * dt,+ };+ }++ const ang = velocity.angular;+ if (ang.x !== 0 || ang.y !== 0 || ang.z !== 0) {+ // Exponential map: rotate by |ω|·dt around ω̂ in the world frame —+ // exact for constant angular velocity at any step size (no drift+ // to renormalize away).+ const q = transform.rotation;+ const mag = Math.hypot(ang.x, ang.y, ang.z);+ const half = mag * dt * 0.5;+ const s = Math.sin(half) / mag;+ const dw = Math.cos(half), dx = ang.x * s, dy = ang.y * s, dz = ang.z * s;+ transform.rotation = {+ w: dw * q.w - dx * q.x - dy * q.y - dz * q.z,+ x: dw * q.x + dx * q.w + dy * q.z - dz * q.y,+ y: dw * q.y - dx * q.z + dy * q.w + dz * q.x,+ z: dw * q.z + dx * q.y - dy * q.x + dz * q.w,+ };+ }+ }+ },+ { name: 'VelocitySystem' }+);++export const velocityPlugin: Plugin = {+ name: 'Velocity',+ build(app) {+ app.addSystemToSchedule(Schedule.Update, velocitySystem, { runIf: playModeOnly });+ },+};diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.tsindex 5ee6db609..d6a207c14 100644--- a/sdk/src/webAppFactory.ts+++ b/sdk/src/webAppFactory.ts@@ -17,6 +17,7 @@ import { tilemapPlugin } from './tilemap';import { postProcessPlugin } from './postprocess';import { timelinePlugin } from './timeline';import { timerPlugin } from './timer';+import { velocityPlugin } from './velocity';import { lifecyclePlugin } from './lifecycle';import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from './ai';import { replicationPlugin } from './net/replication';@@ -35,7 +36,7 @@ export interface CreateWebAppOptions extends WebAppOptions {wasmBaseUrl?: string;}-const basePlugins = [timerPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin];+const basePlugins = [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin];export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {const sideModules: SideModuleHost | undefined = options?.sideModules@@ -57,7 +58,7 @@ export interface HeadlessAppOptions {// (particles, tilemap render, post-process, timeline, UI, spine) stay out —// they exist to be seen.const headlessBasePlugins = (): Plugin[] => [- timerPlugin, lifecyclePlugin, audioPlugin,+ timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin,];diff --git a/sdk/tests/velocity.test.ts b/sdk/tests/velocity.test.tsnew file mode 100644index 000000000..5ae7f8b42--- /dev/null+++ b/sdk/tests/velocity.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeEach } from 'vitest';+import { World } from '../src/world';+import { SystemRunner } from '../src/system';+import { ResourceStorage, Time } from '../src/resource';+import { EventRegistry } from '../src/event';+import { Transform, Velocity, defineComponent } from '../src/component';+import { velocitySystem } from '../src/velocity';+import { createMockModule } from './mocks/wasm';++describe('VelocitySystem', () => {+ let world: World;+ let resources: ResourceStorage;+ let runner: SystemRunner;++ beforeEach(() => {+ world = new World();+ const mod = createMockModule();+ world.connectCpp(mod.getRegistry(), mod);+ resources = new ResourceStorage();+ resources.insert(Time, { delta: 0.5, elapsed: 0, frameCount: 0 } as never);+ runner = new SystemRunner(world, resources, new EventRegistry());+ });++ it('integrates linear velocity into position', () => {+ const e = world.spawn();+ world.insert(e, Transform, { position: { x: 1, y: 2, z: 0 } });+ world.insert(e, Velocity, { linear: { x: 10, y: -4, z: 0 } });++ runner.run(velocitySystem);++ const t = world.get(e, Transform)!;+ expect(t.position.x).toBeCloseTo(6);+ expect(t.position.y).toBeCloseTo(0);+ expect(t.position.z).toBeCloseTo(0);+ });++ it('integrates z angular velocity as planar rotation', () => {+ const e = world.spawn();+ world.insert(e, Transform, {});+ world.insert(e, Velocity, { angular: { x: 0, y: 0, z: Math.PI } });++ runner.run(velocitySystem);++ // 90° around z: q = (cos45°, 0, 0, sin45°). First-order integration+ // renormalized — allow a small tolerance.+ const q = world.get(e, Transform)!.rotation;+ expect(q.w).toBeCloseTo(Math.SQRT1_2, 1);+ expect(q.z).toBeCloseTo(Math.SQRT1_2, 1);+ expect(q.x).toBeCloseTo(0);+ expect(q.y).toBeCloseTo(0);+ });++ it('skips entities owned by the physics solver', () => {+ const RigidBody = defineComponent('RigidBody', { bodyType: 0 });+ const e = world.spawn();+ world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });+ world.insert(e, Velocity, { linear: { x: 100, y: 0, z: 0 } });+ world.insert(e, RigidBody, {});++ runner.run(velocitySystem);++ expect(world.get(e, Transform)!.position.x).toBe(0);+ });++ it('leaves entities without Velocity untouched', () => {+ const e = world.spawn();+ world.insert(e, Transform, { position: { x: 7, y: 8, z: 9 } });++ runner.run(velocitySystem);++ expect(world.get(e, Transform)!.position).toEqual({ x: 7, y: 8, z: 9 });+ });+});diff --git a/src/esengine/ecs/components/Velocity.hpp b/src/esengine/ecs/components/Velocity.hppindex 08349898d..6bf6012fc 100644--- a/src/esengine/ecs/components/Velocity.hpp+++ b/src/esengine/ecs/components/Velocity.hpp@@ -28,10 +28,12 @@ namespace esengine::ecs {// =============================================================================/**- * @brief Velocity component for physics simulation+ * @brief Velocity component for simple kinematic motion*- * @details Stores linear and angular velocity for movement and rotation.- * Used by physics systems to update Transform components.+ * @details Stores linear and angular velocity. The SDK's VelocitySystem+ * integrates it into Transform every Update in play mode; entities+ * owned by the physics solver (RigidBody) are skipped so the two+ * never double-move an entity.** @note Angular velocity is in radians per second around each axis.*/