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(cocos): BoxCollider and Collider are views on the engine's BoxCollider3D, in the node's units, with the static body a collider without a rigid body is

yhhc1e65b695f10
diff --git a/sdk/src/cocos/collider.ts b/sdk/src/cocos/collider.ts
new file mode 100644
index 000000000..b6617ce53
--- /dev/null
+++ b/sdk/src/cocos/collider.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/collider.ts
+ * @brief `Collider` and `BoxCollider`: views on the engine's `BoxCollider3D`.
+ *
+ * A Cocos box is described in the node's own units (`size`, `center`) and takes the node's scale on top; the engine's box holds its half
+ * extents already scaled, which is how the importer writes it. The view converts at the boundary, so a script that reads `size` gets what it
+ * set and the engine's box is the size it is drawn at. A collider with no rigid body is a static one in Cocos; the engine spells that as a static
+ * body beside the box, which adding the collider here puts there.
+ */
+import { BoxCollider3D, RigidBody3D } from '../physics3d/Physics3DComponents';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import { Component } from './component';
+import { registerBuiltinComponent } from './builtins';
+import { Vec3 } from './math';
+import { viewAdapter } from './ui/view';
+
+/** The base of every collider a script asks for. */
+export class Collider extends Component {}
+
+const axes = ['x', 'y', 'z'] as const;
+
+export class BoxCollider extends Collider {
+ private data_() { return this._world.get(this._entity, BoxCollider3D); }
+ private patch_(fields: Record<string, unknown>): void {
+ this._world.set(this._entity, BoxCollider3D, { ...this.data_(), ...fields } as never);
+ }
+ /** The node's scale along an axis; a flat axis would divide by nothing, so it counts as one. */
+ private scaleOf_(axis: 'x' | 'y' | 'z'): number {
+ const s = Math.abs(this.node.scale[axis]);
+ return s > 1e-6 ? s : 1;
+ }
+
+ /** Whether the collider takes part. */
+ get enabled(): boolean { return this.data_().enabled; }
+ set enabled(v: boolean) { this.patch_({ enabled: v }); }
+
+ /** A trigger reports overlaps and pushes nothing. */
+ get isTrigger(): boolean { return this.data_().isSensor; }
+ set isTrigger(v: boolean) { this.patch_({ isSensor: v }); }
+
+ /** The full size of the box, in the node's units. */
+ get size(): Vec3 {
+ const h = this.data_().halfExtents;
+ return new Vec3((h.x * 2) / this.scaleOf_('x'), (h.y * 2) / this.scaleOf_('y'), (h.z * 2) / this.scaleOf_('z'));
+ }
+ set size(v: Vec3) {
+ const half = {} as Record<string, number>;
+ for (const a of axes) half[a] = (Math.abs(v[a]) * this.scaleOf_(a)) / 2;
+ this.patch_({ halfExtents: half });
+ }
+
+ /** Where the box stands from the node's origin, in the node's units. */
+ get center(): Vec3 {
+ const c = this.data_().center ?? { x: 0, y: 0, z: 0 };
+ return new Vec3(c.x / this.scaleOf_('x'), c.y / this.scaleOf_('y'), c.z / this.scaleOf_('z'));
+ }
+ set center(v: Vec3) {
+ const at = {} as Record<string, number>;
+ for (const a of axes) at[a] = v[a] * this.scaleOf_(a);
+ this.patch_({ center: at });
+ }
+}
+
+const hasBox = (world: World, entity: Entity): boolean => world.has(entity, BoxCollider3D);
+const addBox = (world: World, entity: Entity): void => {
+ if (!world.has(entity, RigidBody3D)) world.insert(entity, RigidBody3D, { bodyType: 0 });
+ // Cocos's default box is one unit each way
+ world.insert(entity, BoxCollider3D, { halfExtents: { x: 0.5, y: 0.5, z: 0.5 } });
+};
+registerBuiltinComponent(BoxCollider, ['cc.BoxCollider', 'BoxCollider'], viewAdapter(BoxCollider, hasBox, addBox));
diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.ts
index 980359972..d5ca11044 100644
--- a/sdk/src/cocos/index.ts
+++ b/sdk/src/cocos/index.ts
@@ -30,6 +30,7 @@ export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';
export { unsupported } from './unsupported';
export { ccenum, js, NodePool, profiler } from './misc';
export { MeshRenderer, ModelRenderer, UIMeshRenderer } from './meshRenderer';
+export { Collider, BoxCollider } from './collider';
export { UIRenderer } from './ui/renderer';
export { geometry } from './geometry';
export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, Line, EditBox, PageView, PageViewIndicator, ScrollBar, SafeArea, WebView, getVisibleSize, setVisibleSize } from './ui';
diff --git a/sdk/tests/cocos/collider-wasm.test.ts b/sdk/tests/cocos/collider-wasm.test.ts
new file mode 100644
index 000000000..0b8c1e551
--- /dev/null
+++ b/sdk/tests/cocos/collider-wasm.test.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file `BoxCollider` against the real engine: a script adds one, sets its size and centre in the node's units, and the engine's box holds
+ * them scaled by the node, with a static body beside it.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import type { ESEngineModule } from '../../src/wasm';
+import { World } from '../../src/ecs/world';
+import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
+import { AppContext, setDefaultContext } from '../../src/ecs/context';
+import { BoxCollider3D, RigidBody3D } from '../../src/physics3d/Physics3DComponents';
+import { BoxCollider, Node, Vec3, setCurrentWorld } from '../../src/cocos';
+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
+
+describe.skipIf(!HAS_WASM)('BoxCollider on the engine', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let world: World | undefined;
+
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => {
+ setCurrentWorld(null);
+ world?.disconnectCpp();
+ registry?.delete();
+ registry = undefined;
+ world = undefined;
+ });
+
+ function node(): Node {
+ setDefaultContext(new AppContext());
+ registry = new module.Registry();
+ world = new World();
+ world.connectCpp(registry, module);
+ setCurrentWorld(world);
+ const n = new Node('building');
+ world.insert(n._entity, Transform);
+ return n;
+ }
+
+ it('is made by addComponent with a unit box and a static body', () => {
+ const n = node();
+ const c = n.addComponent(BoxCollider)!;
+ expect(c).toBeInstanceOf(BoxCollider);
+ expect(n.getComponent(BoxCollider)).toBe(c);
+ expect(world!.get(n._entity, RigidBody3D).bodyType).toBe(0);
+ const s = c.size;
+ expect([s.x, s.y, s.z]).toEqual([1, 1, 1]);
+ });
+
+ it('reads back the size and centre it was given, whatever the node scale', () => {
+ const n = node();
+ n.setScale(new Vec3(2, 4, 1));
+ const c = n.addComponent(BoxCollider)!;
+ c.size = new Vec3(1, 1.5, 1);
+ c.center = new Vec3(0, 0.75, 0);
+ c.isTrigger = true;
+ const half = world!.get(n._entity, BoxCollider3D).halfExtents;
+ expect([half.x, half.y, half.z]).toEqual([1, 3, 0.5]);
+ expect(world!.get(n._entity, BoxCollider3D).center.y).toBe(3);
+ expect(world!.get(n._entity, BoxCollider3D).isSensor).toBe(true);
+ expect([c.size.x, c.size.y, c.size.z]).toEqual([1, 1.5, 1]);
+ expect(c.center.y).toBeCloseTo(0.75, 6);
+ expect(c.isTrigger).toBe(true);
+ });
+});