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(editor): unify .tmj object-group shapes into one edit-visible region path

yhhd851b6ef8dd6
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index dce9cc56e..46aa43934 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -153,15 +153,22 @@ if (new URLSearchParams(location.search).has('automation')) {
liveMarkers: () => {
const w = EngineHost.world;
const md = getComponent('Marker');
- const rb = getComponent('RigidBody');
if (!w || !md) return [];
+ const colliders = ['BoxCollider', 'CircleCollider', 'PolygonCollider', 'ChainCollider']
+ .map((n) => getComponent(n)).filter((c): c is NonNullable<typeof c> => !!c);
return w.getEntitiesWithComponents([md]).map((rt) => {
const m = w.get(rt, md) as { type?: string; properties?: Record<string, string> };
+ // A point Marker has no collider (sensor: null); a region has one — sensor=true is a
+ // Trigger Area, sensor=false is solid geometry (a `collision`-group wall).
+ let sensor: boolean | null = null;
+ for (const cd of colliders) {
+ if (w.has(rt, cd)) { sensor = !!(w.get(rt, cd) as { isSensor?: boolean }).isSensor; break; }
+ }
return {
rt,
type: typeof m?.type === 'string' ? m.type : null,
properties: m?.properties ?? {},
- isTrigger: !!(rb && w.has(rt, rb)), // a Trigger Area carries a RigidBody + sensor collider
+ sensor,
src: SceneModel.sourceFor(rt) ?? null,
};
});
diff --git a/examples/tilemap-demo/assets/maps/level.tmj b/examples/tilemap-demo/assets/maps/level.tmj
index 8f59ae333..29941a676 100644
--- a/examples/tilemap-demo/assets/maps/level.tmj
+++ b/examples/tilemap-demo/assets/maps/level.tmj
@@ -10,8 +10,8 @@
"height": 18,
"tilewidth": 18,
"tileheight": 18,
- "nextlayerid": 7,
- "nextobjectid": 6,
+ "nextlayerid": 8,
+ "nextobjectid": 7,
"tilesets": [
{
"firstgid": 1,
@@ -2478,6 +2478,19 @@
"visible":true,
"x":0,
"y":0
+ },
+ {
+ "draworder":"topdown",
+ "id":7,
+ "name":"collision",
+ "objects":[
+ {"id":6,"name":"wall","type":"wall","point":false,"x":470,"y":55,"width":22,"height":118,"rotation":0,"visible":true,"properties":[]}
+ ],
+ "opacity":1,
+ "type":"objectgroup",
+ "visible":true,
+ "x":0,
+ "y":0
}
]
}
\ No newline at end of file
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index f081c4d25..686b2a6a7 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -8,7 +8,7 @@ export {
parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,
generateTileCollision, generateLayerCollision, generateChunkCollision,
generateChunkPolygonCollision, generateChunkTileShapes, generateLayerTileShapes,
- tiledObjectgroupShape, tiledCollisionMods, generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup,
+ tiledObjectgroupShape, tiledCollisionMods, generateObjectCollision, spawnObjectRegion, isCollisionObjectGroup,
polygonLocalVerts, tileColliderShape, oneWayNormalWorld, resolveRelativePath, packCollectionGrid,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
type TiledCollectionTile, type CollectionGridTile,
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index decd66bfe..600bddea4 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -779,31 +779,34 @@ function objectPropsRecord(obj: TiledObjectData): Record<string, string> {
}
/**
- * @brief Project ONE Tiled SHAPE object (rect / ellipse / polygon) into a real Trigger-Area
- * entity — the same shape a hand-authored Trigger Area preset builds: Transform +
- * Marker{type,properties} + static RigidBody + a SENSOR collider matching the shape.
+ * @brief Project ONE Tiled SHAPE object (rect / ellipse / polygon / polyline) into a real
+ * REGION entity — the same shape a hand-authored Trigger Area preset builds:
+ * Transform + Marker{type,properties} + static RigidBody + a collider matching the
+ * shape. `sensor` picks the flavour: a non-collision group's regions are SENSORS
+ * (trigger zones), a `collision` group's regions are SOLID geometry (walls/floors) —
+ * one derivation for both, so every shape object becomes a queryable, gizmo-visible
+ * entity instead of an invisible play-only collider or unqueried `objectGroups` data.
*
- * The converged target for imported object-group regions: instead of living only inside
- * `getTilemapSource().objectGroups`, a region becomes a parented, RuntimeOnly (re-derived,
- * never serialized) entity so it's `Query(Marker)`-able and shows the collider gizmo in the
- * editor — exactly like a hand-placed Trigger Area. LOCAL coords (the tilemap parent carries
- * the origin), mirroring the tile-object sprites; geometry is metres (÷ ppu) like
- * {@link generateObjectCollision}. Point / polyline / gid objects project elsewhere → null.
+ * LOCAL coords (the tilemap parent carries the origin), mirroring the tile-object sprites;
+ * geometry is metres (÷ ppu) like {@link generateObjectCollision}. rect → Box, ellipse →
+ * Circle, polygon ≤8 verts → Polygon (>8 → bounding-box Box), polyline → open Chain.
+ * Point / gid objects project elsewhere (Marker / Sprite) → null.
*/
-export function spawnObjectTriggerArea(
+export function spawnObjectRegion(
world: World,
obj: TiledObjectData,
parent: Entity,
pixelsPerUnit: number,
+ sensor: boolean,
): Entity | null {
- if (obj.shape !== 'rect' && obj.shape !== 'ellipse' && obj.shape !== 'polygon') return null;
+ if (obj.gid !== undefined || obj.shape === 'point') return null;
const rad = obj.rotation * DEG_TO_RAD;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
// Local shape centre (parent = tilemap origin) — generateObjectCollision's spawnAt with
// origin 0; Tiled rotates clockwise about the object anchor (y-down), realized as -rot z.
const spawnAt = (lx: number, ly: number): Entity => {
- const e = world.spawn(obj.name || `Trigger_${obj.id}`);
+ const e = world.spawn(obj.name || `Region_${obj.id}`);
const position = { x: obj.x + lx * cos - ly * sin, y: -(obj.y + lx * sin + ly * cos), z: 0 };
if (rad !== 0) {
const half = -rad * 0.5;
@@ -821,27 +824,36 @@ export function spawnObjectTriggerArea(
const e = spawnAt(obj.width * 0.5, obj.height * 0.5);
world.insert(e, BoxCollider, {
halfExtents: { x: obj.width * 0.5 / pixelsPerUnit, y: obj.height * 0.5 / pixelsPerUnit },
- isSensor: true,
+ isSensor: sensor,
});
return e;
}
if (obj.shape === 'ellipse') {
const e = spawnAt(obj.width * 0.5, obj.height * 0.5);
- world.insert(e, CircleCollider, { radius: (obj.width + obj.height) * 0.25 / pixelsPerUnit, isSensor: true });
+ world.insert(e, CircleCollider, { radius: (obj.width + obj.height) * 0.25 / pixelsPerUnit, isSensor: sensor });
return e;
}
- // polygon (needs ≥ 3 points = 6 flat coords)
- if (!obj.vertices || obj.vertices.length < 6) return null;
+ // polygon / polyline — local vertices flip Tiled's y-down into the body's y-up space.
+ if (!obj.vertices || obj.vertices.length < 4) return null;
const local: { x: number; y: number }[] = [];
for (let i = 0; i < obj.vertices.length; i += 2) {
local.push({ x: obj.vertices[i] / pixelsPerUnit, y: (0 - obj.vertices[i + 1]) / pixelsPerUnit });
}
+ if (obj.shape === 'polyline') {
+ // An open chain is solid geometry only (ChainCollider has no sensor mode) — a
+ // trigger region wants a closed area, so a sensor-group polyline is skipped.
+ if (sensor) return null;
+ const e = spawnAt(0, 0);
+ world.insert(e, ChainCollider, { points: local, isLoop: false });
+ return e;
+ }
+ if (local.length < 3) return null; // a polygon needs at least a triangle
if (local.length <= 8) {
const e = spawnAt(0, 0);
- world.insert(e, PolygonCollider, { vertices: local, isSensor: true });
+ world.insert(e, PolygonCollider, { vertices: local, isSensor: sensor });
return e;
}
- // > 8 verts: Box2D's cap — a bounding-box sensor (predictably shaped, never truncated).
+ // > 8 verts: Box2D's cap — a bounding-box region (predictably shaped, never truncated).
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (let i = 0; i < obj.vertices.length; i += 2) {
const vx = obj.vertices[i], vy = obj.vertices[i + 1];
@@ -851,7 +863,7 @@ export function spawnObjectTriggerArea(
const e = spawnAt((minX + maxX) * 0.5, (minY + maxY) * 0.5);
world.insert(e, BoxCollider, {
halfExtents: { x: (maxX - minX) * 0.5 / pixelsPerUnit, y: (maxY - minY) * 0.5 / pixelsPerUnit },
- isSensor: true,
+ isSensor: sensor,
});
return e;
}
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 922c732b7..360af31bc 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -16,7 +16,7 @@ import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery'
import type { ResolvedTileCollision } from './tilesetResolve';
import {
generateLayerCollision, generateLayerTileShapes, generateChunkCollision, generateChunkTileShapes,
- generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup, decodeTiledGid,
+ spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid,
} from './tiledLoader';
import { decodeTilemapChunks } from './chunkCodec';
import { Assets } from '../asset/AssetPlugin';
@@ -511,18 +511,19 @@ export class TilemapPlugin implements Plugin {
// rotation-invariant). Pixel-verified against Tiled's rendering.
for (const group of cached.objectGroups ?? []) {
if (group.visible === false) continue;
- // A `collision` group's shapes are SOLID geometry (walls/floors) —
- // the play-mode collider path handles them; a non-collision group's
- // shapes are trigger REGIONS → Trigger-Area entities below.
+ // A `collision` group's shapes are SOLID geometry (walls/floors);
+ // every other group's shapes are trigger REGIONS (sensors). Both
+ // derive through the SAME region path below — edit+play visible.
const isCollision = isCollisionObjectGroup(group);
for (const obj of group.objects) {
if (obj.visible === false) continue;
// Non-tile objects converge to real, parented, RuntimeOnly
// entities (re-derived from the .tmj each load, like the
// tile-object sprites), so imported and hand-authored objects
- // share ONE `Query(Marker)` surface: a POINT → a Marker (spawn
- // point / waypoint); a rect/ellipse/polygon in a non-collision
- // group → a Trigger Area (Marker + sensor collider, gizmo-visible).
+ // share ONE `Query(Marker)` surface + collider gizmo: a POINT →
+ // a Marker (spawn point / waypoint); a rect/ellipse/polygon/
+ // polyline → a Region (Marker + collider, sensor unless the
+ // group is `collision`, in which case solid geometry).
if (obj.gid === undefined) {
if (obj.shape === 'point') {
// Carry the Tiled object's custom properties (stringified) so
@@ -535,9 +536,9 @@ export class TilemapPlugin implements Plugin {
world.insert(markerChild, RuntimeOnly, {});
world.setParent(markerChild, entity);
children.push(markerChild);
- } else if (!isCollision) {
- const trigger = spawnObjectTriggerArea(world, obj, entity, pixelsPerUnit);
- if (trigger != null) children.push(trigger);
+ } else {
+ const region = spawnObjectRegion(world, obj, entity, pixelsPerUnit, !isCollision);
+ if (region != null) children.push(region);
}
continue;
}
@@ -590,15 +591,15 @@ export class TilemapPlugin implements Plugin {
this.sourceDerivedFrom_.set(entity, cached);
}
+ // Object-group colliders (solid + sensor) are derived as RuntimeOnly region
+ // entities above (edit+play, gizmo-visible); only TILE collision spawns
+ // here, play-mode only.
const hasTileCollision = !!(cached.collisionTileIds && cached.collisionTileIds.length > 0);
const hasTileShapes = !!(cached.tileShapes && cached.tileShapes.size > 0);
- const collisionGroups = cached.objectGroups
- ? cached.objectGroups.filter(isCollisionObjectGroup)
- : [];
if (
playMode
&& !collisionEntities.has(entity)
- && (hasTileCollision || hasTileShapes || collisionGroups.length > 0)
+ && (hasTileCollision || hasTileShapes)
) {
const tf = world.tryGet(entity, Transform) as
{ position: { x: number; y: number } } | null;
@@ -646,14 +647,6 @@ export class TilemapPlugin implements Plugin {
}
}
}
- // Tiled OBJECT layers marked as collision spawn static colliders
- // alongside the tile-derived ones — same origin, same play-mode
- // lifecycle (dropped on stop, regenerated next Play).
- if (collisionGroups.length > 0) {
- spawned.push(...generateObjectCollision(
- world, collisionGroups, ox, oy, pixelsPerUnit,
- ));
- }
collisionEntities.set(entity, spawned);
}
}
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
index aec51d521..9c7abda0e 100644
--- a/sdk/tests/tilemap.test.ts
+++ b/sdk/tests/tilemap.test.ts
@@ -15,7 +15,7 @@ import {
} from '../src/tilemap/tilesetCache';
import {
loadTiledMap, parseTmjJson, parseTmjWithExternals, resolveRelativePath, loadTiledCollisionObjects,
- generateLayerCollision, generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup, decodeTiledGid,
+ generateLayerCollision, generateObjectCollision, spawnObjectRegion, isCollisionObjectGroup, decodeTiledGid,
packCollectionGrid,
type TiledObjectData, type TiledObjectGroupData,
} from '../src/tilemap/tiledLoader';
@@ -25,7 +25,7 @@ import type { TilesetAsset } from '../src/tilemap/tilesetAsset';
import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';
import { TilemapAssetLoader } from '../src/asset/loaders/TilemapAssetLoader';
import type { LoadContext } from '../src/asset/AssetLoader';
-import { BodyType, RigidBody, BoxCollider, CircleCollider, PolygonCollider } from '../src/physics/PhysicsComponents';
+import { BodyType, RigidBody, BoxCollider, CircleCollider, PolygonCollider, ChainCollider } from '../src/physics/PhysicsComponents';
import { clearUserComponents, Transform, Marker } from '../src/component';
import type { World } from '../src/world';
import type { Entity } from '../src/types';
@@ -1436,7 +1436,7 @@ describe('loadTiledMap — collision integration', () => {
expect(entities).toHaveLength(1);
});
- describe('spawnObjectTriggerArea (object → Trigger Area convergence)', () => {
+ describe('spawnObjectRegion (object → Trigger-Area / solid-region convergence)', () => {
const obj = (over: Partial<Record<string, unknown>>) => ({
id: 7, name: 'gate', type: 'door', visible: true, rotation: 0,
x: 100, y: 50, width: 40, height: 20, vertices: null,
@@ -1444,10 +1444,10 @@ describe('loadTiledMap — collision integration', () => {
...over,
}) as never;
- it('rect → parented Marker + static body + SENSOR box (metres), custom props carried', () => {
+ it('rect (sensor) → parented Marker + static body + SENSOR box (metres), props carried', () => {
const world = createMockWorld();
const parent = world.spawn();
- const e = spawnObjectTriggerArea(world, obj({ shape: 'rect' }), parent, 100);
+ const e = spawnObjectRegion(world, obj({ shape: 'rect' }), parent, 100, true);
expect(e).not.toBeNull();
expect(world.get(e!, Marker)).toEqual({ type: 'door', properties: { event: 'open' } });
expect(world.get(e!, RigidBody).bodyType).toBe(0); // Static
@@ -1458,20 +1458,29 @@ describe('loadTiledMap — collision integration', () => {
expect(world.setParent).toHaveBeenCalledWith(e, parent);
});
- it('ellipse → SENSOR circle on the mean semi-axis', () => {
+ it('sensor=false → the SAME shape as a SOLID collider (collision-group geometry)', () => {
const world = createMockWorld();
- const e = spawnObjectTriggerArea(world, obj({ shape: 'ellipse', width: 80, height: 40 }), world.spawn(), 100);
- const c = world.get(e!, CircleCollider);
+ const e = spawnObjectRegion(world, obj({ shape: 'rect' }), world.spawn(), 100, false);
+ expect(world.get(e!, BoxCollider).isSensor).toBe(false);
+ expect(world.get(e!, RigidBody).bodyType).toBe(0);
+ });
+
+ it('ellipse → circle on the mean semi-axis; polyline → open chain', () => {
+ const world = createMockWorld();
+ const c = world.get(spawnObjectRegion(world, obj({ shape: 'ellipse', width: 80, height: 40 }), world.spawn(), 100, true)!, CircleCollider);
expect(c.isSensor).toBe(true);
expect(c.radius).toBeCloseTo((80 + 40) * 0.25 / 100);
+ const chain = world.get(spawnObjectRegion(world, obj({ shape: 'polyline', vertices: [0, 0, 10, 0, 10, 10] }), world.spawn(), 100, false)!, ChainCollider);
+ expect(chain.isLoop).toBe(false);
+ // A sensor-group polyline is skipped (open chains have no sensor mode).
+ expect(spawnObjectRegion(world, obj({ shape: 'polyline', vertices: [0, 0, 10, 10] }), world.spawn(), 100, true)).toBeNull();
});
- it('polygon (≤8 pts) → SENSOR polygon; point/polyline → null (projected elsewhere)', () => {
+ it('polygon (≤8 pts) → polygon; point / gid → null (projected elsewhere)', () => {
const world = createMockWorld();
- const poly = spawnObjectTriggerArea(world, obj({ shape: 'polygon', vertices: [0, 0, 30, 0, 30, 30] }), world.spawn(), 100);
- expect(world.get(poly!, PolygonCollider).isSensor).toBe(true);
- expect(spawnObjectTriggerArea(world, obj({ shape: 'point' }), world.spawn(), 100)).toBeNull();
- expect(spawnObjectTriggerArea(world, obj({ shape: 'polyline', vertices: [0, 0, 10, 10] }), world.spawn(), 100)).toBeNull();
+ expect(world.get(spawnObjectRegion(world, obj({ shape: 'polygon', vertices: [0, 0, 30, 0, 30, 30] }), world.spawn(), 100, true)!, PolygonCollider).isSensor).toBe(true);
+ expect(spawnObjectRegion(world, obj({ shape: 'point' }), world.spawn(), 100, true)).toBeNull();
+ expect(spawnObjectRegion(world, obj({ shape: 'rect', gid: 5 }), world.spawn(), 100, true)).toBeNull();
});
});