Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Migration to bevy_ecs_tiled v0.16

This guide outlines the steps required to migrate your project to version 0.16 of bevy_ecs_tiled.

This version still targets Bevy v0.20: there is no Bevy upgrade involved, only bevy_ecs_tiled API changes.

Main Changes

  • Dynamic maps: a map can now be modified after it has been loaded. Tilemaps, objects visuals, image sprites and physics colliders are derived from tiles, objects and images entities during PostUpdate. See the Modify a map at runtime guide and the map_dynamic example.
  • Tiles are direct children of their layer, next to the tilemaps rendering them.
  • Tileset, layer and object IDs are no longer standalone components, and IDs now have dedicated types.
  • New modules layout and a smaller prelude.
  • Physics: backends only create colliders, and TiledColliderStrategy replaces both the backends variants and the name filters of TiledPhysicsSettings. It can be set for the whole map, or for a given layer or object.

Migration Steps

1. Update Dependencies

bevy = "0.20"
bevy_ecs_tiled = "0.16"

2. Modules and Prelude

The bevy_ecs_tiled::tiled module has been split by layer: asset (loading Tiled files), ecs (entities holding Tiled data), render (rendering derived from these entities) and properties. If you only use the prelude, the only change is that advanced items left it:

  • the tiled, geo and regex crates are re-exported at the crate root: use bevy_ecs_tiled::{tiled, geo, regex}; instead of bevy_ecs_tiled::prelude::{tiled, geo, regex},
  • collider_shapes(), multi_polygon_as_line_strings(), multi_polygon_as_triangles() and TiledColliderShape, mainly used to write a custom physics backend: use bevy_ecs_tiled::physics::geometry::*;,
  • tiled_debug_gizmos_enabled(): use bevy_ecs_tiled::debug::tiled_debug_gizmos_enabled;.

If you use full paths, update them:

BeforeAfter
tiled::TiledPluginTiledPlugin (crate root)
tiled::sets::*sets::*
tiled::map::asset::TiledMapAssetasset::map::TiledMapAsset
tiled::map::loader::TiledMapLoaderErrorasset::map::TiledMapLoaderError
tiled::world::asset::TiledWorldAssetasset::world::TiledWorldAsset
tiled::world::loader::TiledWorldLoaderErrorasset::world::TiledWorldLoaderError
tiled::{map, world, layer, tile, object, image, event, filter}::*ecs::{map, world, layer, tile, object, image, event, filter}::*
tiled::world::chunking::*ecs::world::streaming::* (see Worlds)
tiled::animation::TiledAnimationrender::animation::TiledAnimation
tiled::tile::TiledTilemaprender::tilemap::TiledTilemap
tiled::object::{TiledObjectVisualOf, TiledObjectVisuals, TiledObjectTextBox, TiledObjectText}render::object::*
tiled::properties::export_typesproperties::export_types

Items of the render module only exist with the render feature (see Running without the render feature).

3. Plugin Configuration

TiledPluginConfig has been removed: its fields are now directly on TiledPlugin, only with the user_properties feature, and have been renamed. Types are no longer exported by default: set types_export_file to keep exporting them.

// Before
App::new().add_plugins(TiledPlugin(TiledPluginConfig {
    tiled_types_export_file: Some(path),
    tiled_types_filter: filter,
}));

// After
App::new().add_plugins(TiledPlugin {
    types_export_file: Some(path),
    types_filter: filter,
});

4. Derived Entities and Tiles Hierarchy

MapCreated, LayerCreated, TileWithPropertiesCreated and ObjectCreated events are now sent before tilemaps, objects visuals, image sprites and physics colliders are spawned. These are spawned later in the same frame, in PostUpdate. If you relied on them in one of these event handlers:

  • use TiledEvent<TilemapCreated> for tilemaps: it is sent each time a tilemap is spawned, including after the map has been loaded, and is no longer ordered with other *Created events,
  • use TiledEvent<ColliderCreated> for physics colliders,
  • use an On<Add<TiledObjectVisualOf>> observer, or a regular system, for objects visuals,
  • use a regular system, running after TiledPostUpdateSystems::SyncRender, for image sprites.

Do not modify derived components, such as the Sprite of an image: they are overwritten when their source changes.

Tiles are no longer children of their TiledTilemap: both are now direct children of their TiledLayer::Tiles. To retrieve the tilemap of a tile, use its TilemapId component instead of its ChildOf component:

// Before (v0.15)
fn system(tiles: Query<&ChildOf, With<TiledTile>>, tilemaps: Query<&GlobalTransform, With<TiledTilemap>>) {
    for child_of in tiles.iter() {
        let tilemap_transform = tilemaps.get(child_of.parent());
    }
}

// After (v0.16)
fn system(tiles: Query<&TilemapId, With<TiledTile>>, tilemaps: Query<&GlobalTransform, With<TiledTilemap>>) {
    for tilemap_id in tiles.iter() {
        let tilemap_transform = tilemaps.get(tilemap_id.0);
    }
}

Tilemaps are created when needed and despawned once empty: you should not spawn them yourself.

5. IDs

Removed ID components

The TiledTilesetId and TiledTileId components have been removed: these IDs are now fields of the TiledTile and TiledTilemap components.

// Before (v0.15)
fn system(tiles: Query<(&TiledTilesetId, &TiledTileId), With<TiledTile>>) { /* ... */ }

// After (v0.16)
fn system(tiles: Query<&TiledTile>) { /* tile.tileset_id, tile.tile_id */ }

Use Changed<TiledTile> instead of Changed<TiledTilesetId> / Changed<TiledTileId>.

The TiledLayerId and TiledObjectId components have been removed, along with the APIs relying on them:

RemovedReplacement
TiledEvent::layer_id(), object_id()layer_entity(), object_entity()
TiledEvent::layer(), object()query the components of the layer or object entity

To read the class or custom properties of the map, a layer or an object, use the new TiledProperties component, which is available even without the user_properties feature:

// Before (v0.15)
fn on_object(event: On<TiledEvent<ObjectCreated>>, assets: Res<Assets<TiledMapAsset>>) {
    let Some(object) = event.event().object(&assets) else { return };
    info!("{:?}", object.properties);
}

// After (v0.16)
fn on_object(event: On<TiledEvent<ObjectCreated>>, objects: Query<&TiledProperties>) {
    let Ok(properties) = objects.get(event.origin) else { return };
    info!("{} {:?}", properties.class, properties.properties);
}

Dedicated ID types

IDs are not plain u32 anymore. The tile ID is still a tiled::TileId.

TypeIDMain APIs
TilesetIdtileset of a mapTiledTile, TiledTilemap, TiledObject::Tile, TiledEvent::tilemap_tileset_id(), TiledMapAsset::tileset(), TiledMapAsset::tile()
LayerIdTiled layer IDTiledMapAsset::layer()
ObjectIdTiled object IDTiledMapAsset::object()
WorldMapIdindex of a map in its .world fileTiledWorldReference, TiledWorldMaps::map_entity()

Wrap the raw value to build an ID, and use .0 or u32::from() to read it:

// Before (v0.15)
let layer = layer_from_map(&map_asset.map, 3);
let map_entity = world_storage.map_entity(1);

// After (v0.16)
let layer = map_asset.layer(LayerId(3));
let map_entity = world_maps.map_entity(world_entity, WorldMapId(1));

Map helper functions

Helper functions taking a tiled::Map have been replaced by methods and fields of TiledMapAsset, which also handle tilesets only used by object templates:

BeforeAfter
tileset_from_map(&map_asset.map, id)map_asset.tileset(id)
tile_from_map(&map_asset.map, tileset_id, tile_id)map_asset.tile(tileset_id, tile_id)
layer_from_map(&map_asset.map, id)map_asset.layer(id), which also finds group layers
object_from_map(&map_asset.map, id)map_asset.object(id)
tilemap_type_from_map(&map_asset.map)map_asset.map_type
try_tilemap_type_from_map(&map)removed: maps with an unsupported orientation fail to load
grid_size_from_map(&map_asset.map)map_asset.grid_size
tile_size(&tile)map_asset.tile_size(&tiled_tile)

6. Events

  • TileCreated has been renamed TileWithPropertiesCreated: as before, it is only sent for tiles with custom properties, when the map is loaded. It no longer holds tilemap information: tilemap_entity() and tilemap_tileset_id() return None, use tile_tileset_id() instead.
  • TiledEvent can no longer be built nor sent from outside the crate: new(), transmute(), with_*() and send() are now private. If you sent your own TiledEvents, define your own event type instead.
  • The type parameter of TiledEvent<E> is bound by the new sealed TiledEventKind trait: replace E: Debug + Clone + Copy + Reflect by E: TiledEventKind in your generic code.
  • TiledEvent is no longer a Component.

7. Map, Layers, Objects and Images

The TiledMapStorage component has been removed. Use the new TiledMapLayers, TiledMapTiles and TiledMapObjects system parameters, which work like a Query restricted to the entities of a given map:

RemovedReplacement
TiledMapStorage::layers()TiledMapLayers<Entity>::iter(map)
TiledMapStorage::objects()TiledMapObjects<Entity>::iter(map)
TiledMapStorage::tiles()TiledMapTiles<(Entity, &TiledTile)>::iter(map)
TiledMapStorage::tile_entities()TiledMapTiles<(Entity, &TiledTile)>::iter(map), filtered on the TiledTile
TiledMapStorage::layer_entity(), object_entity() (and other lookups by Tiled ID)iterate over TiledMapLayers / TiledMapObjects
TiledMapStorage::tile_id(), tile()the TiledTile component of the tile entity, and TiledMapAsset::tile()
// Before (v0.15)
fn on_map_created(
    event: On<TiledEvent<MapCreated>>,
    maps: Query<&TiledMapStorage>,
    tiles: Query<&TilePos>,
) {
    let Ok(storage) = maps.get(event.origin) else { return };
    for (_, entities) in storage.tiles() {
        for position in entities.iter().filter_map(|e| tiles.get(*e).ok()) { /* ... */ }
    }
}

// After (v0.16)
fn on_map_created(event: On<TiledEvent<MapCreated>>, tiles: TiledMapTiles<&TilePos>) {
    for position in tiles.iter(event.origin) { /* ... */ }
}

Entities are given in no particular order. To find the tile at a given position, use the new TiledTileLayerStorage component of its layer.

  • TiledMapAsset::tile_relative_position() takes the TiledTile instead of its size, and returns an Option<Vec2> (None if the tile does not exist in the map). You can also use the new TiledMapHelper system parameter, which only needs the tile entity: maps.tile_relative_position(tile_entity).
  • TiledLayerParallax::parallax_x and parallax_y are merged into parallax: Vec2.
  • TiledObject::kind() has been removed: TiledObject implements Display instead (format!("{object}")).
  • TiledObject::center(), vertices(), line_string() and polygon() are no longer public: use TiledMapAsset::object_center(), object_vertices(), object_line_string() and object_polygon(), which only need the object and its GlobalTransform.
  • TiledObject::Text::font_size is now a f32.
  • TiledObject::from_object_data() now takes the TiledMapAsset as first argument.
  • TiledObjectVisualOf no longer requires a Sprite, and is also inserted on the TiledObjectTextBox of text objects: do not assume that a visual entity has a Sprite.
  • TiledName::matches() has been removed: use filter.matches(&name.0) instead.

TiledObject::Tile now holds the tile it references. Use TiledMapAsset::tileset() and TiledMapAsset::tile() to read the corresponding Tiled data: its tileset can be only used by a template, which is not part of the tiled::Map tilesets.

TiledObject::Tile {
    width: f32,
    height: f32,
    tileset_id: TilesetId,
    tile_id: tiled::TileId,
    flip_x: bool,
    flip_y: bool,
}

TiledImage now holds all the image data and is not Copy anymore. To change the image, modify this component instead of the Sprite.

pub struct TiledImage {
    pub image: Handle<Image>,
    pub base_position: Vec2,
    pub base_size: Vec2,
    pub repeat_x: bool,
    pub repeat_y: bool,
}

8. Worlds

Tiled worlds (.world files) support is now behind the world feature. It is enabled by default: if you disable default features and use Tiled worlds, enable it explicitly.

bevy_ecs_tiled = { version = "0.16", default-features = false, features = ["render", "world"] }

Without it, worlds related APIs do not exist: TiledWorld, RespawnTiledWorld, TiledWorldAsset, TiledWorldStreaming, TiledWorldReference, TiledWorldMaps, WorldMapId, TiledWorldLoaderError, TiledEvent<WorldCreated>, TiledEvent::world_entity(), world_asset(), world() and TiledDebugWorldStreamingPlugin.

The TiledWorldStorage component has been removed. Each map of a world now has a TiledWorldReference component, giving its world entity and its WorldMapId, and the new TiledWorldMaps system parameter works like a Query restricted to the spawned maps of a given world:

RemovedReplacement
TiledWorldStorage::maps()TiledWorldMaps<(Entity, &TiledWorldReference)>::iter(world)
TiledWorldStorage::map_entity(id)TiledWorldMaps::map_entity(world, id)
TiledWorldStorage::map_id(entity)the TiledWorldReference component of the map entity
// Before (v0.15)
fn system(worlds: Query<&TiledWorldStorage>) {
    for storage in worlds.iter() {
        for (map_id, map_entity) in storage.maps() { /* ... */ }
    }
}

// After (v0.16)
fn system(worlds: Query<Entity, With<TiledWorld>>, maps: TiledWorldMaps<(Entity, &TiledWorldReference)>) {
    for world in worlds.iter() {
        for (map_entity, world_map) in maps.iter(world) { /* world_map.map_id() */ }
    }
}

TiledWorldChunking has been renamed TiledWorldStreaming, to avoid confusion with physics colliders chunks and infinite maps chunks, and is now an enum:

// Before
TiledWorldChunking(None)
let area: Option<Vec2> = world_chunking.0;

// After
TiledWorldStreaming::Disabled
let area: Option<Vec2> = world_streaming.area();

TiledWorldStreaming::new() works as TiledWorldChunking::new() did. Related renames:

  • TiledPostUpdateSystems::HandleWorldChunking is now HandleWorldStreaming,
  • TiledDebugWorldChunkPlugin and TiledDebugWorldChunkConfig are now TiledDebugWorldStreamingPlugin and TiledDebugWorldStreamingConfig, whose world_chunk_color field is now streaming_area_color,
  • the world_chunking example is now world_streaming.

If you set TiledWorldChunking from Tiled custom properties, export your types again and use TiledWorldStreaming instead.

9. Physics

  • TiledPreUpdateSystems::SpawnPhysicsColliders has been removed: use TiledPostUpdateSystems::SyncPhysics.
  • Colliders are spawned again when their source changes: you can receive TiledEvent<ColliderCreated> several times for the same source.
  • Modifying TiledPhysicsSettings no longer respawns the map or the world: only physics colliders are spawned again.
  • TiledEvent<ColliderCreated>::tiles() has been removed: query the TiledTile children of the layer instead (TiledTile, TilePos, TileFlip).
  • ColliderCreated::collider_of and ColliderCreated::new() have been removed: the event origin is the collider entity. Use TiledEvent::source_entity(), or the TiledColliderOf component of the collider entity, to retrieve its source.
  • Colliders of tiles layers now take tiles flips into account, which can change their shape.
  • simplify_geometry() has been removed: use geo::unary_union to merge polygons. The TiledPhysicsSettings::simplify_geometry setting is unchanged.

Collider strategy

How colliders are created from Tiled shapes is no longer selected by the physics backend: TiledPhysicsAvianBackend and TiledPhysicsRapierBackend are now unit structs, and their variants moved to the new TiledColliderStrategy enum, set in TiledPhysicsSettings:

// Before
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
    backend: TiledPhysicsAvianBackend::Triangulation,
    ..default()
}

// After
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
    collider_strategy: TiledColliderStrategy::Triangulation,
    ..default()
}

TiledColliderStrategy is also a component: insert it on a layer or an object entity to override the map strategy for this layer or object only.

Selecting which layers and objects get colliders

The name filters of TiledPhysicsSettings have been replaced by the new TiledColliderStrategy::Disabled variant, which disables colliders for a whole map, or for a given layer or object:

BeforeAfter
objects_layer_filterInsert TiledColliderStrategy::Disabled on the objects layers which should not get colliders
objects_filterInsert TiledColliderStrategy::Disabled on the objects which should not get colliders
tiles_layer_filterInsert TiledColliderStrategy::Disabled on the tiles layers which should not get colliders
tiles_objects_filterRenamed tile_shapes_filter

To keep selecting them by name, insert the component from an observer of TiledEvent<LayerCreated> or TiledEvent<ObjectCreated>, or set it from Tiled using a custom property:

// Before
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
    tiles_layer_filter: TiledFilter::from(["collision"]),
    ..default()
}

// After: disable colliders for the whole map, but enable them for the layer named "collision"
commands
    .spawn((
        TiledMap(asset_server.load("map.tmx")),
        TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
            collider_strategy: TiledColliderStrategy::Disabled,
            ..default()
        },
    ))
    .observe(
        |layer_created: On<TiledEvent<LayerCreated>>,
         layers_query: Query<&TiledName, With<TiledLayer>>,
         mut commands: Commands| {
            let layer = layer_created.origin;
            if layers_query.get(layer).is_ok_and(|name| name.0 == "collision") {
                commands.entity(layer).insert(TiledColliderStrategy::Polyline);
            }
        },
    );

Colliders entities

  • The first collider of a tiles layer or an object is always inserted on the layer or object entity itself. This was already the case with the provided backends. The only exception is when the colliders of a tiles layer are split in chunks, a new opt-in feature: the first collider of each chunk is then inserted on a TiledColliderChunk entity, child of the layer.
  • Additional colliders (TiledColliderStrategy::LineStrip, or geometry simplification disabled) are children of this entity, named TiledCollider(<index>) instead of Avian[...] / Rapier[...]. They now also have the TiledColliderOf, TiledColliderSource and TiledColliderPolygons components, and a TiledEvent<ColliderCreated> is sent for each of them.
  • TiledColliderPolygons holds the geometry its collider was created from, instead of all the polygons of the layer or object.

Custom physics backends

The TiledPhysicsBackend trait no longer spawns entities: it only creates the colliders for a given geometry, and bevy_ecs_tiled inserts them on the right entities and removes them when their source changes.

// Before
impl TiledPhysicsBackend for MyBackend {
    fn spawn_colliders(
        &self,
        commands: &mut Commands,
        source: TiledColliderSource,
        origin: Entity,
        multi_polygons_list: Vec<geo::MultiPolygon<f32>>,
    ) -> Option<Entity> {
        /* spawn an entity with a collider */
    }
}

// After
impl TiledPhysicsBackend for MyBackend {
    // The component(s) making a collider
    type Collider = MyCollider;

    fn colliders(
        &self,
        strategy: TiledColliderStrategy,
        source: TiledColliderSource,
        geometry: &TiledColliderGeometry,
    ) -> Vec<Self::Collider> {
        /* return the collider(s) for this geometry */
    }
}
  • colliders() is called once for each geometry: a single time if geometry simplification is enabled (the default).
  • The geometry is a TiledColliderGeometry: its polygons replace the former MultiPolygon, and its outline() gives the segments to use for colliders made of segments (it does not include the edges shared with adjacent colliders chunks).
  • The new physics::geometry::collider_shapes() helper converts a geometry into TiledColliderShapes according to the requested strategy.
  • If you need access to the World to build your collider (eg. to add an asset), use component hooks or observers on your collider component: see the physics_custom example.
  • multi_polygon_as_line_strings() now returns an iterator over borrowed line strings instead of a Vec.

10. System Sets

TiledPostUpdateSystems has three new variants, which run in this order after HandleMapAssetEvents and before Bevy transform and visibility propagation: SyncTiles, SyncRender and SyncPhysics. If you order your systems against map rendering or colliders, use these sets.

TiledUpdateSystems::UpdateTiledImagePositionAndSize has been removed: repeated images position and size are updated during TiledPostUpdateSystems::SyncRender.

11. Features

Custom properties

With the user_properties feature:

  • tile objects now inherit the custom properties of their tile, as in the Tiled editor. Their own properties take precedence,
  • tile properties are also inserted on tiles and tile objects spawned after the map has been loaded. Object references in these properties cannot be resolved: they are set to Entity::PLACEHOLDER.

Running without the render feature

Without the render feature, nothing is displayed and images and texture atlas layouts are no longer loaded, so a map can be loaded on a headless server. It only requires this minimal set of plugins:

App::new().add_plugins((
    MinimalPlugins,
    AssetPlugin::default(),
    TiledPlugin::default(),
));

You can remove ImagePlugin and TextureAtlasPlugin if you only added them for bevy_ecs_tiled.

The TiledObject and TiledImage entities are still spawned with their data, including the content of text objects, but the render module does not exist: objects have no visual, image layers have no Sprite, and TiledImage::image, TiledAnimation, TiledTilemap* and TiledObjectVisual* / TiledObjectText* do not exist. If you displayed them without the render feature, enable it.

The text and debug features now enable the render feature: disable them too to run without it.

12. Non-Exhaustive Enums

TiledObject and the TiledPreUpdateSystems, TiledUpdateSystems and TiledPostUpdateSystems system sets are now #[non_exhaustive], so new variants can be added without a breaking change: add a wildcard arm (_ => ...) when matching on them.

13. Immutable Components and Private Fields

The following components are now immutable: they cannot be queried with &mut nor modified with get_mut(). They are set by bevy_ecs_tiled and are not meant to be modified; if you really need to, insert them again.

TiledMapReference, TiledLayer, TiledTilemap, TiledName, TiledColliderSource and TiledColliderPolygons.

Some fields are no longer public:

BeforeAfter
map_reference.0map_reference.entity() or *map_reference
animation.frames (TiledAnimation)animation.frames()

TiledAnimation::current_frame and timer are internal state and are no longer accessible.

Resources