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(tilemap): Tiled object layers reach the scene runtime - collision groups spawn real colliders, object data queryable
yhh778677eb2f70
diff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.tsindex f99cdd8be..d9182d4ba 100644--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts@@ -53,6 +53,7 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {collisionTileIds: mapData.collisionTileIds,tileAnimations: mapData.tileAnimations,tileProperties: mapData.tileProperties,+ objectGroups: mapData.objectGroups,});return { sourceId: path };diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex d472981e6..c91fce575 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -6,7 +6,8 @@ export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';export {parseTiledMap, parseTmjJson, loadTiledMap, loadTiledCollisionObjects,generateTileCollision, generateLayerCollision, generateChunkCollision,- generateChunkPolygonCollision, polygonLocalVerts, resolveRelativePath,+ generateChunkPolygonCollision, generateObjectCollision, isCollisionObjectGroup,+ polygonLocalVerts, resolveRelativePath,type TiledMapData, type TiledLayerData, type TiledTilesetData,type TiledObjectData, type TiledObjectGroupData, type TiledObjectShape,type TiledAnimFrame, type TilemapLoadOptions,diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex 52c4f9519..7154e2e28 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -37,7 +37,7 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {}}}-import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, BodyType } from '../physics/PhysicsComponents';+import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, ChainCollider, BodyType } from '../physics/PhysicsComponents';import { mergeCollisionTiles } from './collisionMerge';import { CHUNK_SIZE } from './chunkCodec';import { tileIdOf, tileFlagsOf } from './tileBits';@@ -76,9 +76,15 @@ export interface TiledTilesetData {tileCount: number;}-export type TiledObjectShape = 'rect' | 'ellipse' | 'polygon' | 'point';+export type TiledObjectShape = 'rect' | 'ellipse' | 'polygon' | 'polyline' | 'point';export interface TiledObjectData {+ /** Tiled's per-map unique object id. */+ id: number;+ name: string;+ /** The object's class (the field Tiled called `type` before 1.9). */+ type: string;+ visible: boolean;shape: TiledObjectShape;x: number;y: number;@@ -91,6 +97,8 @@ export interface TiledObjectData {export interface TiledObjectGroupData {name: string;+ visible: boolean;+ properties: Map<string, unknown>;objects: TiledObjectData[];}@@ -261,7 +269,7 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | nullvertices.push(pt.x, pt.y);}} else if (obj.polyline) {- shape = 'polygon';+ shape = 'polyline';const linePts = obj.polyline as Array<{ x: number; y: number }>;vertices = [];for (const pt of linePts) {@@ -269,6 +277,10 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null}}parsed.push({+ id: (obj.id as number) ?? 0,+ name: (obj.name as string) ?? '',+ type: (obj.type as string) ?? (obj.class as string) ?? '',+ visible: obj.visible !== false,shape,x: (obj.x as number) ?? 0,y: (obj.y as number) ?? 0,@@ -279,8 +291,17 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | nullproperties: props,});}+ const groupProps = new Map<string, unknown>();+ const rawGroupProps = layer.properties as Array<Record<string, unknown>> | undefined;+ if (rawGroupProps) {+ for (const p of rawGroupProps) {+ groupProps.set(p.name as string, p.value);+ }+ }objectGroups.push({name: (layer.name as string) ?? '',+ visible: layer.visible !== false,+ properties: groupProps,objects: parsed,});}@@ -504,72 +525,145 @@ export interface TilemapLoadOptions {const DEG_TO_RAD = Math.PI / 180;-export function loadTiledCollisionObjects(+/**+ * True when a Tiled object group is authored as collision geometry: a+ * `collision=true` group property (mirroring the tile-property convention) or+ * the group being named `collision` (case-insensitive).+ */+export function isCollisionObjectGroup(group: TiledObjectGroupData): boolean {+ return group.properties?.get('collision') === true+ || group.name.toLowerCase() === 'collision';+}++/**+ * @brief Spawn static colliders for Tiled OBJECT layers (rect / ellipse / polygon / polyline).+ *+ * Same world convention as the tile-collision generators: the map's top-left corner sits at+ * (originX, originY) and Tiled's y-down pixel coordinates descend from it+ * (`world = (originX + px, originY - py)`). Rotation is Tiled's clockwise degrees about the+ * object anchor (top-left for rects/ellipses, the vertex origin for polygons) — realized as+ * the equivalent negative z-rotation on the collider entity, positioned at the true shape+ * centre. Collider GEOMETRY is physics units (metres): pixel sizes divide by pixelsPerUnit,+ * matching `BoxCollider.halfExtents` semantics (positions stay pixels; physics scales those).+ *+ * Shapes: rect → BoxCollider; ellipse → CircleCollider on the mean semi-axis (exact for+ * circles); polygon ≤ 8 vertices → PolygonCollider (Box2D's vertex cap); polygon > 8 →+ * bounding-box BoxCollider with a warning (predictably solid, never silently truncated);+ * polyline → open ChainCollider (the physics layer requires ≥ 4 points); point → skipped+ * (spawn/marker data, queryable from the parsed map).+ */+export function generateObjectCollision(world: World,- mapData: TiledMapData,- mapOriginX: number,- mapOriginY: number,+ groups: TiledObjectGroupData[],+ originX: number,+ originY: number,+ pixelsPerUnit: number = 1,): Entity[] {const entities: Entity[] = [];- const mapPixelH = mapData.height * mapData.tileHeight;-- for (const group of mapData.objectGroups) {+ for (const group of groups) {for (const obj of group.objects) {if (obj.shape === 'point') continue;- const entity = world.spawn();- const tiledX = obj.x;- const tiledY = obj.y;- const worldX = mapOriginX + tiledX + obj.width * 0.5;- const worldY = mapOriginY + (mapPixelH - tiledY) - obj.height * 0.5;- const angle = -obj.rotation * DEG_TO_RAD;-- world.insert(entity, Transform, {- position: { x: worldX, y: worldY, z: 0 },- });- world.insert(entity, RigidBody, { bodyType: BodyType.Static });-- if (obj.shape === 'ellipse') {- const radius = Math.max(obj.width, obj.height) * 0.5;- world.insert(entity, CircleCollider, { radius });- } else if (obj.shape === 'polygon' && obj.vertices) {- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;- for (let i = 0; i < obj.vertices.length; i += 2) {- const vx = obj.vertices[i];- const vy = obj.vertices[i + 1];- if (vx < minX) minX = vx;- if (vx > maxX) maxX = vx;- if (vy < minY) minY = vy;- if (vy > maxY) maxY = vy;+ const rad = obj.rotation * DEG_TO_RAD;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ // Rotate an object-local (y-down) offset about the anchor, then place the+ // anchor-relative point in the world (visually-clockwise rotation is the+ // standard matrix in y-down coordinates).+ const spawnAt = (lx: number, ly: number): Entity => {+ const entity = world.spawn();+ const position = {+ x: originX + obj.x + lx * cos - ly * sin,+ y: originY - (obj.y + lx * sin + ly * cos),+ z: 0,+ };+ if (rad !== 0) {+ const half = -rad * 0.5;+ world.insert(entity, Transform, {+ position,+ rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) },+ });+ } else {+ world.insert(entity, Transform, { position });}- const polyW = maxX - minX;- const polyH = maxY - minY;- const polyCX = (minX + maxX) * 0.5;- const polyCY = (minY + maxY) * 0.5;- world.insert(entity, BoxCollider, {- halfExtents: { x: polyW * 0.5, y: polyH * 0.5 },- offset: { x: polyCX, y: -polyCY },- });- } else {+ world.insert(entity, RigidBody, { bodyType: BodyType.Static });+ entities.push(entity);+ return entity;+ };++ if (obj.shape === 'rect') {+ const entity = spawnAt(obj.width * 0.5, obj.height * 0.5);world.insert(entity, BoxCollider, {- halfExtents: { x: obj.width * 0.5, y: obj.height * 0.5 },+ halfExtents: {+ x: obj.width * 0.5 / pixelsPerUnit,+ y: obj.height * 0.5 / pixelsPerUnit,+ },});- }-- if (angle !== 0) {- const half = angle * 0.5;- world.insert(entity, Transform, {- position: { x: worldX, y: worldY, z: 0 },- rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) },+ } else if (obj.shape === 'ellipse') {+ const entity = spawnAt(obj.width * 0.5, obj.height * 0.5);+ world.insert(entity, CircleCollider, {+ radius: (obj.width + obj.height) * 0.25 / pixelsPerUnit,});+ } else if (obj.vertices && obj.vertices.length >= 4) {+ // Local vertices flip Tiled's y-down into the body's y-up space; the+ // entity's rotation carries the object angle.+ const local: { x: number; y: number }[] = [];+ for (let i = 0; i < obj.vertices.length; i += 2) {+ local.push({+ x: obj.vertices[i] / pixelsPerUnit,+ // binary subtraction: -v would yield -0 for zero components+ y: (0 - obj.vertices[i + 1]) / pixelsPerUnit,+ });+ }+ if (obj.shape === 'polyline') {+ const entity = spawnAt(0, 0);+ world.insert(entity, ChainCollider, { points: local, isLoop: false });+ } else if (local.length <= 8) {+ const entity = spawnAt(0, 0);+ world.insert(entity, PolygonCollider, { vertices: local });+ } else {+ log.warn('tilemap', `object polygon in group '${group.name}' has ${local.length} vertices (Box2D max 8); using its bounding box`);+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (let i = 0; i < obj.vertices.length; i += 2) {+ const vx = obj.vertices[i];+ const vy = obj.vertices[i + 1];+ if (vx < minX) minX = vx;+ if (vx > maxX) maxX = vx;+ if (vy < minY) minY = vy;+ if (vy > maxY) maxY = vy;+ }+ const entity = spawnAt((minX + maxX) * 0.5, (minY + maxY) * 0.5);+ world.insert(entity, BoxCollider, {+ halfExtents: {+ x: (maxX - minX) * 0.5 / pixelsPerUnit,+ y: (maxY - minY) * 0.5 / pixelsPerUnit,+ },+ });+ }}-- entities.push(entity);}}return entities;}+/**+ * @brief Spawn static colliders for EVERY object group of a parsed map (the code-driven+ * `loadTiledMap` path; the scene path filters by {@link isCollisionObjectGroup}).+ *+ * NOTE: behaviour fixed to the shared convention — origin at the map's TOP-left with world-y+ * descending (was bottom-left/y-up, a full map-height off the tiles, the same latent bug the+ * tile path had fixed) and metre-unit collider geometry via `pixelsPerUnit` (was raw pixels).+ */+export function loadTiledCollisionObjects(+ world: World,+ mapData: TiledMapData,+ mapOriginX: number,+ mapOriginY: number,+ pixelsPerUnit: number = 1,+): Entity[] {+ return generateObjectCollision(world, mapData.objectGroups, mapOriginX, mapOriginY, pixelsPerUnit);+}+/*** @brief Greedy-merge a tile grid's collidable cells into static box colliders.*@@ -720,6 +814,7 @@ export function generateChunkPolygonCollision(tileH: number,originX: number,originY: number,+ pixelsPerUnit: number = 1,): Entity[] {const entities: Entity[] = [];if (polygonShapes.size === 0) return entities;@@ -739,8 +834,11 @@ export function generateChunkPolygonCollision(position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },});world.insert(entity, RigidBody, { bodyType: BodyType.Static });+ // PolygonCollider vertices are physics units (uploaded unscaled, like+ // BoxCollider.halfExtents) — divide the pixel-space outline by ppu.world.insert(entity, PolygonCollider, {- vertices: polygonLocalVerts(shape, tileW, tileH, f.flipH, f.flipV, f.flipD),+ vertices: polygonLocalVerts(shape, tileW, tileH, f.flipH, f.flipV, f.flipD)+ .map((v) => ({ x: v.x / pixelsPerUnit, y: v.y / pixelsPerUnit })),});entities.push(entity);}diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 46c68b167..823f8e855 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -10,7 +10,10 @@ import { Tilemap } from './components';import { registerSceneComponentCodec } from '../scene';import { getTilemapSource, getResolvedTileset } from './tilesetCache';import { resolveTilesetModel } from './tilesetResolve';-import { generateLayerCollision, generateChunkCollision, generateChunkPolygonCollision } from './tiledLoader';+import {+ generateLayerCollision, generateChunkCollision, generateChunkPolygonCollision,+ generateObjectCollision, isCollisionObjectGroup,+} from './tiledLoader';import { decodeTilemapChunks } from './chunkCodec';import { Assets } from '../asset/AssetPlugin';import { resolveAssetKey } from '../asset/resolveAssetKey';@@ -221,7 +224,7 @@ export class TilemapPlugin implements Plugin {if (hasPoly) {spawned.push(...generateChunkPolygonCollision(world, chunks, polyShapes,- layerData.cellSize.x, layerData.cellSize.y, ox, oy,+ layerData.cellSize.x, layerData.cellSize.y, ox, oy, pixelsPerUnit,));}collisionEntities.set(entity, spawned);@@ -329,24 +332,38 @@ export class TilemapPlugin implements Plugin {sourceLayerEntities.set(entity, children);}+ const hasTileCollision = !!(cached.collisionTileIds && cached.collisionTileIds.length > 0);+ const collisionGroups = cached.objectGroups+ ? cached.objectGroups.filter(isCollisionObjectGroup)+ : [];if (playMode&& !collisionEntities.has(entity)- && cached.collisionTileIds && cached.collisionTileIds.length > 0+ && (hasTileCollision || collisionGroups.length > 0)) {- const ids = new Set(cached.collisionTileIds);const tf = world.tryGet(entity, Transform) as{ position: { x: number; y: number } } | null;const ox = tf?.position.x ?? 0;const oy = tf?.position.y ?? 0;const spawned: Entity[] = [];- for (const layer of cached.layers) {- // Collision covers finite layers (flat tile arrays);- // infinite/chunk collision is deferred.- if (layer.infinite || layer.tiles.length === 0) continue;- spawned.push(...generateLayerCollision(- world, layer.tiles, layer.width, layer.height,- cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,+ if (hasTileCollision) {+ const ids = new Set(cached.collisionTileIds);+ for (const layer of cached.layers) {+ // Collision covers finite layers (flat tile arrays);+ // infinite/chunk collision is deferred.+ if (layer.infinite || layer.tiles.length === 0) continue;+ spawned.push(...generateLayerCollision(+ world, layer.tiles, layer.width, layer.height,+ cached.tileWidth, cached.tileHeight, ids, ox, oy, pixelsPerUnit,+ ));+ }+ }+ // 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/src/tilemap/tilesetCache.ts b/sdk/src/tilemap/tilesetCache.tsindex a925b100b..43e42c596 100644--- a/sdk/src/tilemap/tilesetCache.ts+++ b/sdk/src/tilemap/tilesetCache.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { ResolvedTileset } from './tilesetResolve';+import type { TiledObjectGroupData } from './tiledLoader';export interface LoadedTilemapChunk {x: number;@@ -39,6 +40,12 @@ export interface LoadedTilemapSource {tileProperties?: Map<number, Map<string, string>>;/** Tile ids flagged collidable (a `collision=true` tile property). Drives runtime collider generation. */collisionTileIds?: number[];+ /**+ * Tiled object layers — spawn/marker data queryable by gameplay via+ * `getTilemapSource`; groups marked per `isCollisionObjectGroup` also spawn+ * static colliders in play mode.+ */+ objectGroups?: TiledObjectGroupData[];}const tilemapCache_ = new Map<string, LoadedTilemapSource>();diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.tsindex 468bfd89c..a8917f336 100644--- a/sdk/tests/tilemap.test.ts+++ b/sdk/tests/tilemap.test.ts@@ -13,7 +13,11 @@ import {getTilemapSource,clearTilemapSourceCache,} from '../src/tilemap/tilesetCache';-import { loadTiledMap, parseTmjJson, resolveRelativePath, loadTiledCollisionObjects, generateLayerCollision } from '../src/tilemap/tiledLoader';+import {+ loadTiledMap, parseTmjJson, resolveRelativePath, loadTiledCollisionObjects,+ generateLayerCollision, generateObjectCollision, isCollisionObjectGroup,+ type TiledObjectData, type TiledObjectGroupData,+} from '../src/tilemap/tiledLoader';import type { TiledMapData } from '../src/tilemap/tiledLoader';import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';import { BodyType } from '../src/physics/PhysicsComponents';@@ -685,6 +689,75 @@ describe('parseTmjJson — Phase B: objectgroup parsing', () => {expect(result!.layers).toHaveLength(1);expect(result!.objectGroups).toHaveLength(1);});++ it('should parse object identity (id/name/type) and visibility', () => {+ const json = {+ width: 10, height: 10, tilewidth: 32, tileheight: 32,+ tilesets: [],+ layers: [{+ type: 'objectgroup',+ name: 'Spawns',+ objects: [+ { id: 7, name: 'player-start', type: 'SpawnPoint', x: 10, y: 20, width: 0, height: 0, point: true, rotation: 0 },+ { id: 8, name: 'hidden', x: 0, y: 0, width: 8, height: 8, rotation: 0, visible: false },+ ],+ }],+ };+ const result = parseTmjJson(json);+ const [a, b] = result!.objectGroups[0].objects;+ expect(a.id).toBe(7);+ expect(a.name).toBe('player-start');+ expect(a.type).toBe('SpawnPoint');+ expect(a.visible).toBe(true);+ expect(b.visible).toBe(false);+ });++ it('should read the Tiled 1.9 class field as type', () => {+ const json = {+ width: 10, height: 10, tilewidth: 32, tileheight: 32,+ tilesets: [],+ layers: [{+ type: 'objectgroup', name: 'G',+ objects: [{ id: 1, class: 'Enemy', x: 0, y: 0, width: 8, height: 8, rotation: 0 }],+ }],+ };+ const result = parseTmjJson(json);+ expect(result!.objectGroups[0].objects[0].type).toBe('Enemy');+ });++ it('should distinguish polylines from polygons', () => {+ const json = {+ width: 10, height: 10, tilewidth: 32, tileheight: 32,+ tilesets: [],+ layers: [{+ type: 'objectgroup', name: 'Terrain',+ objects: [{+ id: 1, x: 0, y: 64, width: 0, height: 0, rotation: 0,+ polyline: [{ x: 0, y: 0 }, { x: 32, y: -16 }, { x: 64, y: 0 }, { x: 96, y: 8 }],+ }],+ }],+ };+ const result = parseTmjJson(json);+ const obj = result!.objectGroups[0].objects[0];+ expect(obj.shape).toBe('polyline');+ expect(obj.vertices).toEqual([0, 0, 32, -16, 64, 0, 96, 8]);+ });++ it('should parse group-level properties and visibility', () => {+ const json = {+ width: 10, height: 10, tilewidth: 32, tileheight: 32,+ tilesets: [],+ layers: [{+ type: 'objectgroup', name: 'Walls', visible: false,+ properties: [{ name: 'collision', type: 'bool', value: true }],+ objects: [{ id: 1, x: 0, y: 0, width: 32, height: 32, rotation: 0 }],+ }],+ };+ const result = parseTmjJson(json);+ const group = result!.objectGroups[0];+ expect(group.visible).toBe(false);+ expect(group.properties.get('collision')).toBe(true);+ });});describe('parseTmjJson — Phase C: collision tile IDs', () => {@@ -819,96 +892,173 @@ describe('loadTiledCollisionObjects', () => {} as unknown as World;}- it('should create entities for rect objects', () => {+ const makeObject = (o: Partial<TiledObjectData>): TiledObjectData => ({+ id: 1, name: '', type: '', visible: true, shape: 'rect', x: 0, y: 0,+ width: 0, height: 0, rotation: 0, vertices: null, properties: new Map(),+ ...o,+ });+ const makeGroup = (name: string, objects: TiledObjectData[], properties?: Map<string, unknown>): TiledObjectGroupData => ({+ name, visible: true, properties: properties ?? new Map(), objects,+ });+ const makeMap = (groups: TiledObjectGroupData[]): TiledMapData => ({+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,+ orientation: 'orthogonal', hexSideLength: 0, staggerAxis: 'y', staggerIndex: 'odd',+ layers: [], tilesets: [], collisionTileIds: [],+ tileAnimations: new Map(), tileProperties: new Map(),+ objectGroups: groups,+ });++ it('should place rect colliders on the tile convention (top-left origin, y-down)', () => {const world = createMockWorld();- const mapData: TiledMapData = {- width: 10, height: 10, tileWidth: 32, tileHeight: 32,- layers: [], tilesets: [], collisionTileIds: [],- objectGroups: [{- name: 'Collision',- objects: [- { shape: 'rect' as const, x: 64, y: 96, width: 32, height: 32, rotation: 0, vertices: null, properties: new Map() },- ],- }],- };+ const mapData = makeMap([makeGroup('Collision', [+ makeObject({ shape: 'rect', x: 64, y: 96, width: 32, height: 32 }),+ ])]);const entities = loadTiledCollisionObjects(world, mapData, 0, 0);expect(entities).toHaveLength(1);- expect(world.spawn).toHaveBeenCalledTimes(1);const insertCalls = (world.insert as any).mock.calls;const rbInsert = insertCalls.find((c: any) => c[1]._name === 'RigidBody');- expect(rbInsert).toBeDefined();expect(rbInsert[2].bodyType).toBe(0);+ // Centre (80, 112) in Tiled pixels -> world (80, -112), like a tile at that spot.+ const tfInsert = insertCalls.find((c: any) => c[1]._name === 'Transform');+ expect(tfInsert[2].position).toEqual({ x: 80, y: -112, z: 0 });+const boxInsert = insertCalls.find((c: any) => c[1]._name === 'BoxCollider');- expect(boxInsert).toBeDefined();- expect(boxInsert[2].halfExtents.x).toBe(16);- expect(boxInsert[2].halfExtents.y).toBe(16);+ expect(boxInsert[2].halfExtents).toEqual({ x: 16, y: 16 });});- it('should create CircleCollider for ellipse objects', () => {+ it('should divide collider geometry by pixelsPerUnit (positions stay pixels)', () => {const world = createMockWorld();- const mapData: TiledMapData = {- width: 10, height: 10, tileWidth: 32, tileHeight: 32,- layers: [], tilesets: [], collisionTileIds: [],- objectGroups: [{- name: 'Collision',- objects: [- { shape: 'ellipse' as const, x: 0, y: 0, width: 64, height: 32, rotation: 0, vertices: null, properties: new Map() },- ],- }],- };+ const mapData = makeMap([makeGroup('Collision', [+ makeObject({ shape: 'rect', x: 64, y: 96, width: 32, height: 32 }),+ ])]);++ loadTiledCollisionObjects(world, mapData, 0, 0, 100);++ const insertCalls = (world.insert as any).mock.calls;+ expect(insertCalls.find((c: any) => c[1]._name === 'Transform')[2].position)+ .toEqual({ x: 80, y: -112, z: 0 });+ expect(insertCalls.find((c: any) => c[1]._name === 'BoxCollider')[2].halfExtents)+ .toEqual({ x: 0.16, y: 0.16 });+ });++ it('should create CircleCollider on the mean semi-axis for ellipse objects', () => {+ const world = createMockWorld();+ const mapData = makeMap([makeGroup('Collision', [+ makeObject({ shape: 'ellipse', x: 0, y: 0, width: 64, height: 32 }),+ ])]);loadTiledCollisionObjects(world, mapData, 0, 0);const insertCalls = (world.insert as any).mock.calls;const circleInsert = insertCalls.find((c: any) => c[1]._name === 'CircleCollider');- expect(circleInsert).toBeDefined();- expect(circleInsert[2].radius).toBe(32);+ expect(circleInsert[2].radius).toBe(24);+ expect(insertCalls.find((c: any) => c[1]._name === 'Transform')[2].position)+ .toEqual({ x: 32, y: -16, z: 0 });});it('should skip point objects', () => {const world = createMockWorld();- const mapData: TiledMapData = {- width: 10, height: 10, tileWidth: 32, tileHeight: 32,- layers: [], tilesets: [], collisionTileIds: [],- objectGroups: [{- name: 'Points',- objects: [- { shape: 'point' as const, x: 10, y: 20, width: 0, height: 0, rotation: 0, vertices: null, properties: new Map() },- ],- }],- };+ const mapData = makeMap([makeGroup('Points', [+ makeObject({ shape: 'point', x: 10, y: 20 }),+ ])]);const entities = loadTiledCollisionObjects(world, mapData, 0, 0);expect(entities).toHaveLength(0);expect(world.spawn).not.toHaveBeenCalled();});- it('should create BoxCollider for polygon using bounding box', () => {+ it('should create a real PolygonCollider (y-flipped local verts) for small polygons', () => {const world = createMockWorld();- const mapData: TiledMapData = {- width: 10, height: 10, tileWidth: 32, tileHeight: 32,- layers: [], tilesets: [], collisionTileIds: [],- objectGroups: [{- name: 'Polys',- objects: [{- shape: 'polygon' as const,- x: 0, y: 0, width: 0, height: 0, rotation: 0,- vertices: [0, 0, 40, 0, 40, 20, 0, 20],- properties: new Map(),- }],- }],- };+ const mapData = makeMap([makeGroup('Polys', [+ makeObject({ shape: 'polygon', x: 16, y: 48, vertices: [0, 0, 40, 0, 40, 20, 0, 20] }),+ ])]);++ loadTiledCollisionObjects(world, mapData, 0, 0);++ const insertCalls = (world.insert as any).mock.calls;+ const polyInsert = insertCalls.find((c: any) => c[1]._name === 'PolygonCollider');+ expect(polyInsert[2].vertices).toEqual([+ { x: 0, y: 0 }, { x: 40, y: 0 }, { x: 40, y: -20 }, { x: 0, y: -20 },+ ]);+ expect(insertCalls.find((c: any) => c[1]._name === 'Transform')[2].position)+ .toEqual({ x: 16, y: -48, z: 0 });+ });++ it('should create an open ChainCollider for polylines', () => {+ const world = createMockWorld();+ const mapData = makeMap([makeGroup('Terrain', [+ makeObject({ shape: 'polyline', x: 0, y: 64, vertices: [0, 0, 32, -16, 64, 0, 96, 8] }),+ ])]);++ loadTiledCollisionObjects(world, mapData, 0, 0, 2);++ const insertCalls = (world.insert as any).mock.calls;+ const chainInsert = insertCalls.find((c: any) => c[1]._name === 'ChainCollider');+ expect(chainInsert[2].isLoop).toBe(false);+ expect(chainInsert[2].points).toEqual([+ { x: 0, y: 0 }, { x: 16, y: 8 }, { x: 32, y: 0 }, { x: 48, y: -4 },+ ]);+ expect(insertCalls.find((c: any) => c[1]._name === 'Transform')[2].position)+ .toEqual({ x: 0, y: -64, z: 0 });+ });++ it('should fall back to the bounding box for polygons over the Box2D vertex cap', () => {+ const world = createMockWorld();+ const verts: number[] = [];+ for (let i = 0; i < 10; i++) {+ const a = (i / 10) * Math.PI * 2;+ verts.push(Math.cos(a) * 50, Math.sin(a) * 50);+ }+ const mapData = makeMap([makeGroup('Blob', [+ makeObject({ shape: 'polygon', x: 100, y: 100, vertices: verts }),+ ])]);loadTiledCollisionObjects(world, mapData, 0, 0);const insertCalls = (world.insert as any).mock.calls;+ expect(insertCalls.find((c: any) => c[1]._name === 'PolygonCollider')).toBeUndefined();const boxInsert = insertCalls.find((c: any) => c[1]._name === 'BoxCollider');- expect(boxInsert).toBeDefined();- expect(boxInsert[2].halfExtents.x).toBe(20);- expect(boxInsert[2].halfExtents.y).toBe(10);+ expect(boxInsert[2].halfExtents.x).toBeCloseTo(50, 3);+ });++ it('should rotate about the object anchor like Tiled (clockwise degrees)', () => {+ const world = createMockWorld();+ const mapData = makeMap([makeGroup('Collision', [+ makeObject({ shape: 'rect', x: 0, y: 0, width: 64, height: 16, rotation: 90 }),+ ])]);++ loadTiledCollisionObjects(world, mapData, 0, 0);++ const insertCalls = (world.insert as any).mock.calls;+ const tf = insertCalls.find((c: any) => c[1]._name === 'Transform')[2];+ // Anchor-pivot rotation moves the centre to (-8, 32) in Tiled pixels -> world (-8, -32).+ expect(tf.position.x).toBeCloseTo(-8, 5);+ expect(tf.position.y).toBeCloseTo(-32, 5);+ // World rotation is the negative angle (y-flip mirrors the direction).+ expect(tf.rotation.z).toBeCloseTo(Math.sin(-Math.PI / 4), 5);+ expect(tf.rotation.w).toBeCloseTo(Math.cos(-Math.PI / 4), 5);+ });+});++describe('isCollisionObjectGroup', () => {+ const group = (name: string, properties?: Map<string, unknown>): TiledObjectGroupData =>+ ({ name, visible: true, properties: properties ?? new Map(), objects: [] });++ it('matches a collision=true group property', () => {+ expect(isCollisionObjectGroup(group('Walls', new Map([['collision', true]])))).toBe(true);+ });++ it('matches a group named collision (case-insensitive)', () => {+ expect(isCollisionObjectGroup(group('Collision'))).toBe(true);+ expect(isCollisionObjectGroup(group('collision'))).toBe(true);+ });++ it('rejects unmarked groups', () => {+ expect(isCollisionObjectGroup(group('Spawns'))).toBe(false);+ expect(isCollisionObjectGroup(group('Walls', new Map([['collision', false]])))).toBe(false);});});