Introduction
bevy_ecs_tiled is a Bevy plugin for working with 2D tilemaps created using the Tiled map editor.
It leverages the official Tiled Rust bindings for parsing and loading Tiled map files, and uses the bevy_ecs_tilemap crate for efficient rendering.
This plugin aims to provide a simple and ergonomic workflow for integrating Tiled into your Bevy 2D games, letting you focus on game design while handling the technical details of map loading, rendering, and entity management.
Features
- Comprehensive Map Support:
Load orthogonal, isometric, or hexagonal maps, with finite or infinite layers, using either external or embedded tilesets, atlases, or multiple images. - Rich Tiled Feature Integration:
Supports animated tiles, image layers, tile objects, and Tiled worlds for multi-map projects. - Entity-Based Architecture:
Every Tiled item (layer, tile, object, etc.) is represented as a Bevy entity, organized in a clear hierarchy: layers are children of the map entity, tiles and objects are children of their respective layers.VisibilityandTransformare automatically propagated. - Dynamic Maps:
Spawn, despawn or modify tiles, objects and images after a map has been loaded: their rendering and physics colliders are automatically updated. - Flexible Map Lifecycle:
Control how maps are spawned and despawned. Use Bevy events and observers to customize scene setup or react when a map is loaded and ready. - Automatic Physics Integration:
Automatically spawn Rapier or Avian physics colliders for tiles and objects, with support for custom backends. - Custom Properties as Components:
Use Tiled custom properties to automatically insert your own components on objects, tiles, or layers, enabling powerful data-driven workflows. - Hot-Reloading:
Edit your maps in Tiled and see updates reflected live in your Bevy game, without recompiling or restarting.
Disclaimer:
Both this book and the whole crate have been heavily inspired by the bevy_ecs_ldtk crate, which is essentially the equivalent of bevy_ecs_tiled but for the LDTK map editor.
A big thank you to the authors and contributors of bevy_ecs_ldtk for their inspiration and ideas!
Purpose of this Book
This book is designed to help you understand how bevy_ecs_tiled works, what you can achieve with it, and how to use it effectively in your projects.
You’ll find:
- High-level concepts and design explanations
- Step-by-step tutorials and practical guides
- Migration guides for upgrading between versions
- Miscellaneous tips and advanced topics
If you need detailed API documentation, please refer to the bevy_ecs_tiled API reference.
The examples directory is also a great place to see the plugin in action.
Note:
This book assumes you already have some familiarity with Bevy and the Tiled map editor.
If you’re new to these tools, check out their official documentation and the useful links section for recommended resources.
Book Structure
This book is organized into several sections:
- Design & Explanation:
Learn how the plugin works internally and the reasoning behind key technical choices. - How-To Guides:
In-depth tutorials covering specific features and workflows. - Migration Guides:
Step-by-step instructions for upgrading between major versions. - Miscellaneous:
Additional topics and tips that don’t fit elsewhere.
Happy reading, and enjoy building your games with Bevy and Tiled!
FAQ
What’s the current status of the crate?
The crate is already quite usable, but it is still under active development.
You may encounter bugs, missing features, or breaking changes as the API evolves. However, the project follows semantic versioning and provides a migration guide for each breaking change (for example, when a new Bevy release is supported).
I try to list all known limitations and bugs of the crate as Github issues.
What kind of maps are supported?
Nearly all map types from Tiled are supported:
- Orthogonal
- “Flat-top” hexagonal
- “Pointy-top” hexagonal
- “Diamond” isometric
Not supported: Isometric “staggered” maps (see issue #31).
While we support isometric maps, we currently do not support isometric tilesets. But you can still use an isometric map with an orthogonal tileset.
I want a huge map for my game, is it a problem?
If you have performance issues with a single large map, consider using a Tiled world. A Tiled world is a collection of multiple maps, and you can control which ones are loaded at any given time.
To spawn a Tiled world, use the TiledWorld component after loading a .world asset:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
// Spawn a new entity with the TiledWorld component
commands.spawn(
TiledWorld(asset_server.load("demo.world"))
);
}
}
You can customize world loading with the same components and events / observers as for maps, and use the TiledWorldStreaming component to only spawn the maps around the camera.
I’m using an isometric map and it seems all messed up!
- Make sure you are actually using a “diamond” isometric map, not a “staggered” one (which is not supported).
- For isometric maps, you may need to tweak the
TilemapRenderSettingscomponent frombevy_ecs_tilemapto enable Y-sorting and adjust the chunk size. - Make sure you are using an orthogonal tileset and not an isometric one.
See the isometric maps example for more information.
How do I add physics to my game?
You can automatically spawn physics colliders on tiles or objects using either the Avian or Rapier physics backends.
All you need to do is add the appropriate plugin to your app—bevy_ecs_tiled handles the rest.
You can control which objects or tiles receive colliders based on their name and by using Tiled’s built-in collision editor. See the dedicated physics guide for details.
How can I update my Bevy entities directly from Tiled?
Suppose you’re building a top-down RPG and want to assign properties (like movement cost or walkability) to each tile.
You can declare in your code some struct or enum to describe these properties then use Tiled custom properties editor to attach these properties to Tiled elements.
The crate will automatically insert the corresponding Bevy Component on the Tiled entity when you load the map, making it available for your game logic.
See the custom properties guide for more information.
Can I modify a map after it has been loaded?
Yes: tiles, objects and images entities hold Tiled data, from which their rendering and physics colliders are derived.
You can spawn, despawn or modify them (for instance change a tile TiledTile or TilePos, or an object TiledObject shape) and their rendering and colliders will automatically follow.
See the dedicated guide for more information and the map_dynamic example for a demo.
Note that respawning a map, for instance when it is hot-reloaded, discards all these modifications: see Spawn / Despawn / Reload a Map.
Can I load a map on a headless server?
Yes: disable the default features, in particular render. The text and debug features both enable it, so do not use them either.
[dependencies]
bevy_ecs_tiled = { version = "0.16", default-features = false }
App::new().add_plugins((
MinimalPlugins,
AssetPlugin::default(),
TiledPlugin::default(),
));
Images and texture atlas layouts are not loaded and nothing is displayed: there are no tilemaps, sprites or texts.
Maps, layers, tiles and objects are still spawned with their data, and you can use the physics feature to get their colliders.
How do I enable map hot-reload?
Enable the Bevy file_watcher feature in your project.
With this enabled, bevy_ecs_tiled will automatically reload a map or world whenever it is updated in Tiled.
Reloading a map respawns it from its asset: all the modifications made to its entities since it has been spawned are lost.
Is this crate WASM compatible?
Yes it is!
All you have to do is to enable the wasm feature flag.
If you want to run one of the crate example you can use the Bevy CLI :
bevy run --example map_basic --features=wasm web
How do I access Tiled “raw” data?
Sometimes you may need to access the underlying Tiled data, such as a tile or the custom properties of an object.
Tiled data are held by ECS components, so you can read them directly from the entities:
- The map, layers and objects have a
TiledPropertiescomponent, which holds their class and custom properties as defined in Tiled, whether theuser_propertiesfeature is enabled or not. - Tiles have a
TiledTilecomponent, which holds their tileset ID and tile ID: useTiledMapAsset::tile()to retrieve the correspondingtiled::Tile. - Objects have a
TiledObjectcomponent, which describes their shape, and aTiledName.
You can also:
- Listen to map loading events and use
TiledEvent<E>helper methods to access the map asset and the entities related to the event. - Use the
TiledMapLayers,TiledMapTilesandTiledMapObjectssystem parameters to list the layers, tiles and objects entities of a map. - Read the
TiledMapAssetdirectly. Note that it is not updated when you modify the map entities after the map has been loaded.
These options are demonstrated in examples and debug plugins.
I found a bug! / Feature ‘X’ is missing! / How do I do ‘Y’?
This crate is still a work in progress, so you may encounter bugs, missing features, or have questions about usage.
- Check the open issues to see if your problem is already reported.
- If not, please open a new issue! I try to address every issue as quickly as possible.
Contributions are very welcome! If you’d like to contribute, please read the contribution guide and feel free to open a PR!
Why use Tiled?
Tiled may feel a bit outdated in terms of “look and feel,” especially compared to more modern map editors like LDTK.
However, Tiled offers a wealth of features that make it a compelling choice for many projects.
If we compare Tiled with LDTK, both editors provide powerful capabilities such as:
- Auto-tiling
- Adding gameplay information to map tiles and objects (custom properties)
- Support for world layouts (multi-map projects)
But Tiled also offers several unique advantages:
- Native support for both isometric and hexagonal maps (including “pointy-top” and “flat-top” hexes)
- Built-in support for animated tiles
For my own needs—specifically, working with hexagonal maps—Tiled was the obvious choice!
However, if you only need orthogonal maps, you might want to try LDTK, especially in combination with the bevy_ecs_ldtk crate.
Of course, Tiled remains a robust and versatile option for a wide range of 2D games.
API Overview
Where to look in the API, depending on what you want to do.
Everything listed here is in the prelude (use bevy_ecs_tiled::prelude::*;), unless a full path is given.
Crate Layout
| Module | Content |
|---|---|
asset | Tiled files loaded as Bevy assets: TiledMapAsset, TiledWorldAsset and Tiled IDs. |
ecs | Entities and components holding the Tiled data: the source of truth, which you can modify. |
render | Rendering derived from the ecs entities (render feature). |
physics | Physics colliders derived from the ecs entities (physics feature). |
properties | Tiled custom properties. |
debug | Debug gizmos (debug feature). |
I Want To…
| I want to… | Use |
|---|---|
| Load a map | Add the TiledPlugin, spawn a TiledMap |
| Load a world | Spawn a TiledWorld (world feature) |
| Only spawn the maps of a world around the camera | TiledWorldStreaming |
| Find the spawned maps of a world | TiledWorldMaps system parameter, TiledWorldReference on the map entity |
| Reload a map | Insert RespawnTiledMap, or a new TiledMap |
| Place the map | TilemapAnchor and Transform on the map entity |
| Change the Z offset between layers | TiledMapLayerZOffset |
| React when a map, layer or object is spawned | An observer on TiledEvent<MapCreated> (or LayerCreated, ObjectCreated, …) |
| Find the map of a layer, tile or object | TiledMapReference, or TiledMapHelper |
| Iterate over the layers, tiles or objects of a map | TiledMapLayers, TiledMapTiles, TiledMapObjects system parameters |
| Find the tile at a given position | TiledTileLayerStorage on the layer entity |
| Know where a tile is displayed | TiledMapHelper::tile_relative_position |
| Modify the map at runtime | Spawn, modify or despawn TiledTile and TiledObject entities (see the guide) |
| Read raw Tiled data | TiledMapAsset (map field, tileset(), tile(), layer(), object()) and the re-exported tiled crate |
| Read custom properties as they are in Tiled | TiledProperties |
| Get custom properties as my own components | The user_properties feature (see the guide) |
| Customize the tilemaps of a layer | An observer on TiledEvent<TilemapCreated>, TiledTilemap |
| Add parallax to layers | TiledParallaxCamera on the camera |
| Add physics colliders | TiledPhysicsPlugin and TiledPhysicsSettings (see the guide) |
| Split tiles colliders into chunks | TiledColliderChunkSize |
| React when colliders are created | An observer on TiledEvent<ColliderCreated> |
| Use another physics engine | TiledPhysicsBackend and physics::geometry::collider_shapes |
Run my systems before or after bevy_ecs_tiled ones | System sets |
| See what is going on | TiledDebugPluginGroup (see the guide) |
Entities Hierarchy and Marker Components
When a map is loaded, it spawns many entities: for the map, for layers, for tiles, for objects, for colliders, and more.
To keep things organized, these entities are structured in a parent/child hierarchy, and every entity has an associated marker component to help with queries and system targeting.
Using a hierarchy also enables inheritance of certain components from top-level entities down the tree.
For example, if you change the Visibility of a layer entity, it will automatically apply to all entities below it in the hierarchy, such as tiles or objects.
Hierarchy Overview
flowchart TD
W["<b>TiledWorld</b><br/>(optional)"]
M["<b>TiledMap</b>"]
LT["<b>TiledLayer::Tiles</b>"]
LO["<b>TiledLayer::Objects</b>"]
LI["<b>TiledLayer::Image</b>"]
LG["<b>TiledLayer::Group</b>"]
LS["other layers..."]
T["<b>TiledTilemap</b><br/>one per tileset"]
TI["<b>TiledTile</b>"]
O["<b>TiledObject</b>"]
OV["<b>TiledObjectVisualOf</b><br/>(tile objects)"]
OB["<b>TiledObjectTextBox</b><br/>(text objects)"]
OT["<b>TiledObjectText</b>"]
I["<b>TiledImage</b>"]
CC["<b>TiledColliderChunk</b><br/>(colliders chunks)"]
C["<b>TiledColliderOf</b><br/>(additional colliders)"]
W --> M
M --> LT & LO & LI & LG
LG --> LS
LT --> T & TI
LO --> O
O --> OV
O --> OB --> OT
LI --> I
LT -.-> CC -.-> C
LT -.-> C
O -.-> C
Dashed arrows are only present when the physics feature is enabled and the corresponding layer or object is selected to produce colliders.
The first collider of a tiles layer or an object is held by the layer or object entity itself, or by its TiledColliderChunk when colliders are split in chunks: only additional colliders get their own entity (see Physics Colliders).
Tiled Data and Derived Entities
Entities spawned by bevy_ecs_tiled fall into two categories:
- Tiled data: the map, layers, tiles, objects and images entities.
They hold what was defined in Tiled, such as a tile
TiledTile(tileset ID and tile ID) andTilePos, or aTiledObjectshape. - Derived entities and components:
TiledTilemaps, tile objects and text objects visuals, imageSprites and physics colliders. They are computed from the Tiled data duringTiledPostUpdateSystems::SyncRenderandTiledPostUpdateSystems::SyncPhysics.
Tiled data are the source of truth: you can spawn, despawn or modify them after the map has been loaded and derived entities will automatically follow. On the other hand, you should not modify derived entities yourself, since your changes could be overwritten.
See Modify a map at runtime for more information.
Most entities spawned by bevy_ecs_tiled share a few common components:
TiledMapReference, for layers, tiles, tilemaps, objects and images: the map entity they belong to, so you do not have to walk up the hierarchy to find it. Object visuals and physics colliders do not have one: use the map reference of their object or layer.TiledName, for layers, objects and tilemaps: the name given in Tiled to the layer, object or tileset.TiledProperties, for the map, layers and objects: their class and custom properties, as defined in Tiled.
TiledMapReference, TiledName, TiledProperties and TiledLayer are immutable components: they cannot be queried mutably, insert a new value instead.
World
A world is the optional top of the tree.
Loading a .world asset gives you a TiledWorld entity, which holds a handle to the corresponding TiledWorldAsset.
Each map of the world is spawned as a child of this entity, with a TiledWorldReference component giving its world and its WorldMapId: use the TiledWorldMaps system parameter to retrieve the spawned maps of a world.
All map-level settings can be added to the world entity: they are propagated down to every underlying map.
Map
Loading a .tmx asset gives you a TiledMap entity, which holds a handle to the corresponding TiledMapAsset.
It is the top of the tree, unless the map belongs to a world.
This is where you put map-level settings, such as the TilemapAnchor or the TiledMapLayerZOffset.
All the entities spawned from the map have a TiledMapReference to the map entity: use the TiledMapLayers, TiledMapTiles and TiledMapObjects system parameters to iterate over the entities of a given map.
Layers
Each Tiled layer is spawned as a child of the map, with a TiledLayer component.
Its value tells you the kind of layer, and what you will find below it:
| Variant | Children |
|---|---|
TiledLayer::Tiles | one TiledTile per tile and one TiledTilemap per tileset |
TiledLayer::Objects | one TiledObject per object |
TiledLayer::Image | a single TiledImage |
TiledLayer::Group | other layers, nested as in Tiled |
Tiles
Below each TiledLayer::Tiles, you find two kinds of sibling entities:
- the actual
TiledTileentities, one for each tile of the layer. TheirTiledTilecomponent gives their tileset ID and tile ID, and they are positioned with aTilePos. - one
TiledTilemapentity per tileset used by the layer, rendering the tiles using this tileset (given by itstileset_idfield). It holds theTilemapBundlefrombevy_ecs_tilemap, so this is where the tilemap size, grid size or texture live. You can reach the tilemaps of a layer through theTiledTilemapsrelationship, and the tilemap of a tile through itsTilemapId.
Tilemaps are derived from tiles: a tilemap is spawned when a tile using a new tileset is added to a layer, and despawned once it does not contain any tile anymore.
A position of a layer can only hold a single tile, as in Tiled.
To find the tile at a given position, use the TiledTileLayerStorage component of the layer (see Modify a map at runtime).
Spawning a tile, or moving a tile (ie. changing its TilePos), onto a position already used by another tile of the same layer despawns this other tile, whatever its tileset.
Note that:
- tiles outside of the map bounds (see
TiledMapAsset::tilemap_size) are neither rendered nor used to compute physics colliders: layers cannot grow, - moving a tile to another layer (ie. changing its
ChildOf) is not supported: despawn it and spawn a new one in the other layer instead.
Objects
Each Tiled object is spawned as a child of its TiledLayer::Objects, with a TiledObject component describing its shape (point, rectangle, polygon, …).
Most objects are a single entity, but two kinds of objects have children holding their visual.
Tile objects
A TiledObject::Tile has a child entity with a TiledObjectVisualOf component, spawned again whenever the TiledObject changes.
This child holds the Sprite of the tile and, if the tile is animated, a TiledAnimation.
From the object entity, you can reach it through the TiledObjectVisuals relationship.
Visual entities and TiledAnimation only exist with the render feature.
Text objects
A TiledObject::Text is rendered using two nested entities, if the text feature is enabled (it is by default):
- a
TiledObjectTextBoxchild, which represents the text box drawn in Tiled: itsAabbhas the size of the box. It also has aTiledObjectVisualOfcomponent: it is spawned again whenever theTiledObjectchanges. - below it, a
TiledObjectTextentity holding the actualText2dandTextFont. ItsAnchorand position inside the box follow the horizontal and vertical alignment set in Tiled.
To change the text content or style at runtime, query the TiledObjectText entity:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn make_texts_red(mut texts: Query<&mut TextColor, Added<TiledObjectText>>) {
for mut color in texts.iter_mut() {
color.0 = Color::srgb(1., 0., 0.);
}
}
}
See the map_text example for a demo.
Images
An image layer has a single TiledImage child.
It holds the image handle, position, size and repeat settings, from which its Sprite is derived.
When the image is repeated along an axis, the sprite size is updated to cover what the camera can see.
Without the render feature, it has no image handle and no Sprite.
Physics Colliders
At the bottom of the hierarchy, you find physics colliders.
They are created for a source entity, either a TiledLayer::Tiles or a TiledObject, and are spawned again when their source changes (for instance when a tile of the layer is added, modified or removed).
Objects
The first collider of an object is inserted on the TiledObject entity itself, so you can directly add other physics components to it.
An object can have several colliders, for instance with TiledColliderStrategy::LineStrip: the next ones are spawned as children of the object entity.
Tiles layers
The tiles of a layer do not get their own colliders: the colliders of all the tiles of a TiledLayer::Tiles are created together, for the layer.
- By default, the first collider is inserted on the layer entity itself, and the next ones, if any, are spawned as children of the layer entity. They are all spawned again whenever a tile of the layer is added, modified or removed.
- When the colliders of the layer are split in chunks, the layer entity does not hold any collider.
Each chunk with at least one collider gets its own
TiledColliderChunkentity, child of the layer, which holds the first collider of the chunk; the next ones are children of the chunk entity. When a tile is modified, only the colliders of its chunk (and of the adjacent chunks) are spawned again.
In both cases, the layer entity remains the source of all these colliders.
Collider components
Each entity holding a collider carries:
- a
TiledColliderOfrelationship pointing to their source entity (possibly itself). On the other side, the source has aTiledColliderscomponent listing all its colliders. - a
TiledColliderSourcecomponent telling whether the collider comes from a tiles layer or from an object. - a
TiledColliderPolygonscomponent holding the raw geometry the collider was created from.
Since a source can have several colliders spread over several entities, add a rigid body to the source entity, given by TiledEvent<ColliderCreated>::source_entity(), rather than to each collider entity.
See the physics guide for more information.
Transform and Visibility Propagation
Bevy automatically propagates Transform and Visibility components down the entity hierarchy.
In practice:
If you change one of these components for a top-level entity (e.g., a layer), it will propagate down and apply to all child entities. For example:
- Adding
Visibility::Hiddento an object layer will hide all objects in that layer. - Moving an object layer will also move all objects it contains.
Special case for tiles:
Tiles are not rendered as individual entities, but as part of a “chunk” of several tiles for performance reasons.
Each individual tile entity does not have its own Transform or Visibility component.
Instead, these components are propagated down to the TiledTilemap, and bevy_ecs_tilemap handles updating the corresponding tile chunks.
Important:
Even though you technically could, you should not addTransformorVisibilitycomponents to individual tile entities:
- It will not have the intended effect—everything is handled at the tilemap level.
- It may hurt performance significantly.
Z-ordering
In 2D games, the Z-axis determines the rendering order: elements with a higher Z value appear in front of those with a lower Z value.
For a deeper dive into Bevy’s coordinate system and Z-ordering, see the Bevy cheatbook.
Layer Ordering in Tiled and Bevy
When designing your map in Tiled, you expect that layers higher in the stack visually cover those below.
This is especially important for isometric maps, which often use multiple tile layers for proper visual stacking.
To reproduce this behavior in Bevy, bevy_ecs_tiled assigns an incremental Z offset to each layer in the hierarchy.
If we call this offset OFFSET:
- The topmost layer (in Tiled) will have a Z transform of
0 - The next layer down will have a Z transform of
-1 × OFFSET - The next one:
-2 × OFFSET - And so on…
By default, OFFSET is set to +100.
You can adjust this value by adding or modifying the TiledMapLayerZOffset component on your map entity.
Tip:
bevy_ecs_tilemapalso applies a small Z offset to each chunk for correct rendering.
If your layer offset is too small, you may see unexpected rendering order issues.
A larger offset (like the default100) helps avoid this.
Objects on a Layer
Objects on a given layer inherit the Z offset of their parent layer, but each object is given a small additional offset to avoid “Z-fighting”—a flickering effect that occurs when two objects share the same Z value.
- Each object receives a unique, small Z offset relative to its parent layer.
- This ensures that overlapping objects are rendered in a stable order.
If you need precise control over the Z position of specific objects (for example, to implement custom sorting or to ensure a particular object always appears on top), you can:
- Listen to map events and manually adjust the Z offset of your objects after they are spawned.
- Use your own logic to set the Z value based on object properties or gameplay needs.
Map Loading Events
When loading a map or a world with bevy_ecs_tiled, you receive events that both notify you about the loading progress and allow you to customize how your map or world is handled in your game.
These events are extremely useful for:
- Running custom logic when a map, layer, object, or tile is loaded
- Accessing or modifying entities as soon as they are available
- Integrating with other systems (e.g., spawning a player, setting up triggers, etc.)
TiledEvent<E>
All bevy_ecs_tiled events are encapsulated in the TiledEvent<E> structure.
This provides more context for each event, including the origin of each particular event E and helper methods to access Tiled data.
For example, an event related to an object will contain not only information to identify the object itself, but also the layer and the map containing it.
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn handle_event(
mut object_events: MessageReader<TiledEvent<ObjectCreated>>,
assets: Res<Assets<TiledMapAsset>>,
) {
// Even though we receive an event for a Tiled object,
// we can retrieve information about the Tiled map
for e in object_events.read() {
let object_entity = e.origin;
if let Some(map_asset) = e.map_asset(&assets) {
info!("Received TiledEvent<ObjectCreated> for: '{:?}'", map_asset);
}
}
}
}
List of Map and World Events
There are six main events:
- For maps and worlds:
TiledEvent<MapCreated>:
Emitted once a map has finished loading. Contains information about the map entity.
(If loading a world, this is called after the world event.)TiledEvent<LayerCreated>:
Emitted for each layer after the map is loaded. Contains information about the layer entity.TiledEvent<TilemapCreated>:
Emitted each time a tilemap is spawned, see below. Contains information about the tilemap entity.TiledEvent<TileWithPropertiesCreated>:
Emitted after the map is loaded for each tile which has custom properties: tiles without any custom property do not get this event. Contains information about the tile entity.TiledEvent<ObjectCreated>:
Emitted for each object after the map is loaded. Contains information about the object entity.
- For worlds only:
TiledEvent<WorldCreated>:
Emitted once the world has finished loading. Contains information about the world entity.
Except for TilemapCreated, all these events are sent after the map or world is fully loaded and all components (including those from user properties) have been inserted.
How to Use Map Events
You can listen to these events in two ways:
1. Using Buffered Events
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn handle_map_event(
mut map_events: MessageReader<TiledEvent<MapCreated>>,
map_query: Query<&Name, With<TiledMap>>,
) {
for e in map_events.read() {
if let Some(map_entity) = e.map_entity() {
if let Ok(name) = map_query.get(map_entity) {
info!("=> Received TiledMapCreated event for map '{}'", name);
}
}
}
}
}
2. Using Observers
Observers can be attached directly to map or world entities.
This is useful for “inline” logic, such as spawning a player when a map is ready:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands
// Spawn a map and attach an observer on it.
.spawn(TiledMap(
asset_server.load("maps/orthogonal/finite.tmx"),
))
// Add an "in-line" observer to detect when the map has finished loading
.observe(|e: On<TiledEvent<MapCreated>>, map_query: Query<&Name, With<TiledMap>>| {
if let Some(map_entity) = e.map_entity() {
if let Ok(name) = map_query.get(map_entity) {
info!("=> Observer TiledMapCreated was triggered for map '{}'", name);
}
}
});
}
}
Events Bubble Up: Beware of Global Observers
Observed events bubble up the entity hierarchy: an observer attached to a world entity also receives the events of all its maps.
While an event bubbles up, TiledEvent::entity is the entity currently observing it, whereas TiledEvent::origin always is the entity the event was sent for (eg. the created layer).
A global observer (ie. added with App::add_observer) runs once for each entity the event bubbles through: it usually receives the same event several times.
Use TiledEvent::is_original() to only handle it once:
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new().add_observer(on_object_created);
}
fn on_object_created(object_created: On<TiledEvent<ObjectCreated>>) {
// Skip the copies of this event received while it bubbles up the hierarchy
if !object_created.is_original() {
return;
}
info!("Object {} created", object_created.origin);
}
If you want to handle all the events of a given kind, whatever the map, a MessageReader is usually simpler: each event is read exactly once.
When Are Events Sent?
All these events are sent after the map or world is actually loaded and all its Tiled data entities (layers, tiles, objects, images) have been spawned, with their components inserted, including those coming from user properties.
This means you can safely query for components and child entities in your event handlers: for instance, when receiving a LayerCreated event, all the other layers of the map already exist.
Events are sent in the following order: MapCreated, then LayerCreated, TileWithPropertiesCreated and finally ObjectCreated.
Note that rendering components and physics colliders are derived from Tiled data later in the frame, during TiledPostUpdateSystems: they do not exist yet when these events are sent.
If you need them, use the ColliderCreated and TilemapCreated events instead.
TilemapCreated Is a Rendering Event
Tilemaps are rendering entities derived from tiles (see Entities hierarchy).
As such, TilemapCreated is sent whenever a tilemap is spawned, during TiledPostUpdateSystems::SyncRender:
- when the map is loaded, once for each layer and tileset combination,
- later on, when a tile using a new tileset is added to a layer.
It is only sent when the render feature is enabled.
Dedicated Example
A dedicated example is available to demonstrate how to use these events in practice.
Coordinates conversion between Tiled and Bevy
Tiled and Bevy do not describe positions the same way.
bevy_ecs_tiled converts everything for you when it spawns a map, but you will need to understand the differences as soon as you want to:
- find which tile is under the cursor,
- place a gameplay entity where an object was drawn in Tiled,
- read raw data from
tiled::Map(themapfield ofTiledMapAsset) and use it in Bevy.
This page explains the two coordinate systems and how bevy_ecs_tiled converts from one to the other.
Two different conventions
| Tiled | Bevy | |
|---|---|---|
| Unit | pixels | world units (1 unit = 1 pixel with a default 2D camera) |
| Origin | top-left corner of the map | the map entity Transform, adjusted by the TilemapAnchor |
| X axis | points right | points right |
| Y axis | points down | points up |
| Tile indexes | (0, 0) is the top-left tile | TilePos { x: 0, y: 0 } is the bottom-left tile |
| Rotation | degrees, clockwise | radians, counter-clockwise |
| Layer offset | (offset_x, offset_y), Y down | (offset_x, -offset_y), Y up |
Tiled Bevy
(0,0) ──────────► +X +Y ▲
│ ┌───┬───┬───┐ │ ┌───┬───┬───┐
│ │0,0│1,0│2,0│ │ │0,2│1,2│2,2│
│ ├───┼───┼───┤ │ ├───┼───┼───┤
│ │0,1│1,1│2,1│ │ │0,1│1,1│2,1│
│ ├───┼───┼───┤ │ ├───┼───┼───┤
│ │0,2│1,2│2,2│ │ │0,0│1,0│2,0│
▼ └───┴───┴───┘ │ └───┴───┴───┘
+Y └──────────────► +X
The X axis is the same in both systems. Almost every conversion therefore comes down to flipping the Y axis and moving the origin.
Converting a Tiled position
Every Tiled pixel position (objects, image layers, map corners, …) is converted by TiledMapAsset::world_space_from_tiled_position.
It returns a position relative to the map entity.
Infinite maps
In an infinite map, Tiled stores tiles in chunks of 16x16 tiles, and chunk indexes can be negative.
bevy_ecs_tilemap does not support negative tile positions, so all chunks are shifted so that the top-left chunk becomes chunk (0, 0):
Tiled chunks TilePos origin
(-1,-1) │ (0,-1) │ (1,-1) ┌────────┬────────┬────────┐
────────┼────────┼──────── │ │ │ │
(-1, 0) │ (0, 0) │ (1, 0) ──► ├────────┼────────┼────────┤
────────┼────────┼──────── │ │ │ │
└────────┴────────┴────────┘
(0,0) ▲ bottom-left tile
The map size used by Bevy (TiledMapAsset::tilemap_size) is the bounding box of all the chunks, not the width / height stored in the .tmx file.
Tiled pixel positions are shifted by the same amount, so objects stay aligned with tiles.
Isometric maps
On isometric (diamond) maps, Tiled object coordinates are not screen pixels.
They are expressed along the two diagonal axes of the grid, in pixels where one tile measures tile_height on both axes:
◆ ← Tiled (0, 0)
╱ ╲
Tiled +Y ╱ ╲ Tiled +X
╱ ╲
◆ map ◆
╲ ╱
╲ ╱
╲ ╱
◆
To get a screen position, bevy_ecs_tiled first projects these coordinates:
fx = tiled.x / tile_height
fy = tiled.y / tile_height
screen.x = (fx - fy) * tile_width / 2 + map_height_in_tiles * tile_width / 2
screen.y = (fx + fy) * tile_height / 2
and then flips the Y axis, as for other orientations.
Since bevy_ecs_tilemap and Tiled do not place isometric tile images the same way, the tilemap entity also receives a small offset so that tiles are rendered exactly where they are in Tiled.
Image layers are positioned relative to Tiled “screen origin”, which, for isometric maps, is located map_height * tile_width / 2 pixels on the left of the top corner of tile (0, 0).
Note: Staggered isometric maps are not supported and are rejected by the map loader.
Hexagonal maps
Hexagonal maps use the same Y flip as orthogonal maps.
However, flipping the Y axis changes which rows (or columns) are “staggered”, so the Tiled stagger settings map to the bevy_ecs_tilemap HexCoordSystem as follows:
| Tiled stagger axis | Tiled stagger index | HexCoordSystem (even map height) | HexCoordSystem (odd map height) |
|---|---|---|---|
| X | Even | ColumnOdd | ColumnOdd |
| X | Odd | ColumnEven | ColumnEven |
| Y | Even | RowOdd | RowEven |
| Y | Odd | RowEven | RowOdd |
When the stagger axis is Y, Tiled row r becomes row height - 1 - r in Bevy: if the map height is odd, flipping the Y axis does not change the rows parity, hence the different coordinate system.
Infinite maps always have an even height (a multiple of the chunk size).
The resulting TilemapType of a map is available in TiledMapAsset::map_type.
Hexagon side length
In Tiled, staggered rows (or columns) are (tile_size + hexsidelength) / 2 pixels apart.
bevy_ecs_tilemap assumes regular hexagons and spaces them by 0.75 * grid_size.
To render the map like Tiled, the grid size is adjusted along the stagger axis:
| Tiled stagger axis | Grid size |
|---|---|
| X | (2 * (tile_width + hexsidelength) / 3, tile_height) |
| Y | (tile_width, 2 * (tile_height + hexsidelength) / 3) |
When hexsidelength is half the tile size, the grid size is the tile size.
Always use TiledMapAsset::grid_size, and not the Tiled tile size, with bevy_ecs_tilemap helpers such as TilePos::center_in_world() or TilePos::from_world_pos().
Worlds
In a .world file, each map position is the Tiled pixel position of its top-left corner, with Y pointing down.
bevy_ecs_tiled flips it so that the world bounding box (TiledWorldAsset::rect) starts at (0, 0) and grows towards positive X and Y.
The TilemapAnchor of a TiledWorld applies to the whole world bounding box, not to each map individually.
Getting started
Add the required dependencies to your Cargo.toml file:
[dependencies]
bevy = "0.20"
bevy_ecs_tiled = "0.16"
Basic Usage
To get started, add the plugin to your app and spawn a map entity.
All you need to do is spawn a TiledMap component with the map asset you want to load (e.g., your map.tmx file).
Make sure this map asset, along with any required dependencies (such as images or tilesets), is present in your local assets folder (by default, ./assets/).
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
// Add Bevy's default plugins
.add_plugins(DefaultPlugins)
// Add the bevy_ecs_tiled plugin
// bevy_ecs_tilemap::TilemapPlugin will be added automatically if needed
.add_plugins(TiledPlugin::default())
// Add your startup system and run the app
.add_systems(Startup, startup)
.run();
}
fn startup(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
// Spawn a 2D camera
commands.spawn(Camera2d);
// Load a map asset and retrieve its handle
let map_handle: Handle<TiledMapAsset> = asset_server.load("map.tmx");
// Spawn a new entity with the TiledMap component
commands.spawn(TiledMap(map_handle));
}
This simple example will load a map using the default settings.
Customizing Map Loading
You can customize how the map is loaded by listening to specific TiledEvent or adding various components to the map entity, such as:
TilemapAnchor— Controls the anchor point of the tilemap.TiledMapLayerZOffset— Adjusts the Z offset between map layers.TiledMapImageRepeatMargin— Control the margin for repeated images.TilemapRenderSettings— Configures rendering options.Transform— Sets the position, rotation, and scale of the map.Visibility— Controls the visibility of the map entity.
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn spawn_map(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
commands
// Load a map and set its anchor point to the
// center instead of the default bottom-left
.spawn((
TiledMap(asset_server.load("map.tmx")),
TilemapAnchor::Center,
))
// Add an "in-line" observer to detect when
// the map has finished loading
.observe(
|map_created: On<TiledEvent<MapCreated>>,
assets: Res<Assets<TiledMapAsset>>,
query: Query<&Name, With<TiledMap>>,
objects: TiledMapObjects<(Entity, &TiledObject)>| {
// We can access the map components via a regular query
let Ok(name) = query.get(map_created.origin) else {
return;
};
info!("=> Observer TiledMapCreated was triggered for map '{name}'");
// Or directly the underneath raw tiled::Map data
let Some(map) = map_created.event().map(&assets) else {
return;
};
info!("Loaded map: {:?}", map);
// Additionally, we can query the Tiled items of this map using the
// TiledMapLayers, TiledMapTiles and TiledMapObjects system parameters.
// This can be useful if you want for instance to create a resource
// based upon tiles or objects data but make it available only when
// the map is actually spawned.
for (entity, object) in objects.iter(map_created.origin) {
info!("(map) {object} object was spawned as entity {entity:?}");
}
}
);
}
}
More Examples
For more advanced use cases, such as loading worlds, chunking, custom properties, or integrating with physics, see the examples directory in the repository and notably the demo_platformer and demo_topdown demos.
You can also refer to the API documentation for details on all available components and configuration options.
Spawn / Despawn / Reload a Map
These aspects are also covered in the dedicated example.
Spawning a Map
Spawning a map is a two-step process:
- Load the map asset using Bevy’s
AssetServer. - Spawn a
TiledMapcontaining a reference to this map asset.
#![allow(unused)]
fn main() {
fn spawn_map(
mut commands: Commands,
asset_server: Res<AssetServer>
) {
// Load the map asset
let map_handle: Handle<TiledMapAsset> = asset_server.load("map.tmx");
// Spawn the map entity with default settings
commands.spawn(TiledMap(map_handle));
}
}
Tip:
You can load maps at startup or at any time during your game.
There is no restriction on the number of maps loaded or spawned simultaneously.
Despawning a Map
To despawn a map, simply remove its top-level entity.
All child entities (layers, tiles, objects, etc.) will be automatically despawned.
#![allow(unused)]
fn main() {
pub fn despawn_map(
mut commands: Commands,
map_query: Query<Entity, With<TiledMap>>,
) {
// Iterate over all map entities
for map in map_query.iter() {
// Despawn the map entity and all its children
commands.entity(map).despawn();
}
}
}
Respawning / Reloading a Map
If you want to reload or respawn a map, you can despawn it and spawn it again as shown above.
However, there is a more ergonomic way: insert the RespawnTiledMap component on the map entity.
#![allow(unused)]
fn main() {
fn respawn_map(
mut commands: Commands,
map_query: Query<Entity, With<TiledMap>>,
) {
if let Ok(entity) = map_query.single() {
commands.entity(entity).insert(RespawnTiledMap);
}
}
}
This will reload the same map asset, despawning and respawning all child entities (layers, tiles, objects, etc.), while preserving the top-level map entity and its components.
- Any changes you made to child entities (e.g., tile color, object position) will be reset to their original state.
- Components on the map entity itself (such as
TilemapRenderSettings,TiledMapLayerZOffset, orTransform) will be preserved.
This is useful for implementing level respawn or resetting a map to its initial state.
Note that the map is also respawned when you modify one of these components on the map entity: TiledMap, TilemapAnchor, TiledMapLayerZOffset or TilemapRenderSettings.
Modifying TiledPhysicsSettings does not respawn the map: only its physics colliders are spawned again.
In all these cases, the modifications you made to the map entities at runtime (spawned, despawned or modified tiles and objects, see Modify a map at runtime) are lost.
Loading a New Map Over an Existing One
To replace the current map with a different one, simply insert a new TiledMap on the existing map entity:
#![allow(unused)]
fn main() {
fn handle_reload(
mut commands: Commands,
asset_server: Res<AssetServer>,
map_query: Query<Entity, With<TiledMap>>,
) {
if let Ok(entity) = map_query.single() {
commands.entity(entity)
.insert(
TiledMap(asset_server.load("other_map.tmx"))
);
}
}
}
- If you insert the same map handle, it is equivalent to inserting the
RespawnTiledMapcomponent.
Summary
- Spawn: Load the map asset and spawn a
TiledMap. - Despawn: Remove the map entity (children are cleaned up automatically).
- Respawn/Reload: Insert
RespawnTiledMapor a newTiledMapto reload or swap maps efficiently.
For more advanced usage, see the examples.
Modify a Map at Runtime
Once a map has been loaded, you can freely modify it: spawn, despawn or modify its tiles, objects and images.
bevy_ecs_tiled takes care of keeping their rendering and their physics colliders up to date.
This is useful to build destructible terrain, open doors, let the player build things, generate parts of a level procedurally, and more.
A dedicated example demonstrates these features.
How It Works
The entities spawned when loading a map fall into two categories:
- Tiled data: the map, its layers, tiles, objects and images entities. They hold what was defined in Tiled: which tile is at which position, the shape of an object, the image of an image layer, …
- Derived entities and components: tilemaps, objects visuals (sprites and texts), images sprites and physics colliders. They are computed from Tiled data and you should not modify them yourself, since your changes would be overwritten.
Tiled data are the source of truth: when they change, derived entities are updated during PostUpdate, in the following TiledPostUpdateSystems sets:
| System set | What is updated |
|---|---|
First | A TiledMapReference is inserted on new tiles and objects which do not have one. |
SyncTiles | Tiles are registered in the TiledTileLayerStorage of their layer, and a tile moved onto another one replaces it. |
SyncRender | Tilemaps, objects visuals and images sprites are spawned, updated or despawned. |
SyncPhysics | Physics colliders are spawned again. |
These sets run before Bevy transform and visibility propagation: if you modify Tiled data during Update (or earlier), the result is visible in the same frame.
See the entities hierarchy page for a description of all the entities composing a map.
Tiles
Each tile is an entity with a TiledTile component, child of its TiledLayer::Tiles entity.
Its Tiled data are held by the following components, which you can freely modify:
| Component | Description |
|---|---|
TiledTile | Tileset of the tile (tileset_id, a TilesetId) and tile in this tileset (tile_id) |
TilePos | Position of the tile in the layer (origin is the bottom-left corner of the map) |
TileFlip | Horizontal, vertical and diagonal flips |
TileVisible, TileColor | Visibility and color of the tile |
Other components, such as TilemapId, TileTextureIndex or AnimatedTile, are derived from these data: do not modify them.
Modify, Move or Despawn a Tile
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
/// Replace tile 0 with tile 1 of the same tileset, everywhere
fn replace_tiles(mut tiles: Query<&mut TiledTile>) {
for mut tile in tiles.iter_mut() {
if tile.tile_id == 0 {
tile.tile_id = 1;
}
}
}
/// Move all the tiles of a layer one step to the right
fn move_tiles(mut tiles: Query<&mut TilePos, With<TiledTile>>) {
for mut tile_pos in tiles.iter_mut() {
tile_pos.x += 1;
}
}
/// Despawn the tile at a given position of a given layer
fn despawn_tile(mut commands: Commands, layers: Query<&TiledTileLayerStorage>) {
let (layer, position) = (Entity::PLACEHOLDER, TilePos::new(3, 4));
// Each layer indexes its tiles by their position
if let Ok(storage) = layers.get(layer)
&& let Some(entity) = storage.get(position)
{
commands.entity(entity).despawn();
}
}
}
When a tile changes, it is moved to the tilemap of its new tileset, and the colliders of its layer are spawned again. A tilemap is spawned when a tile using a new tileset is added to a layer, and despawned once it does not contain any tile anymore.
Spawn a Tile
To spawn a new tile, you only need to provide its Tiled data and its parent layer:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn spawn_tile(mut commands: Commands, layers: Query<(Entity, &TiledLayer)>) {
let Some((layer, _)) = layers.iter().find(|(_, l)| matches!(l, TiledLayer::Tiles)) else {
return;
};
commands.spawn((
// Tile 2 of the first tileset of the map
TiledTile::new(TilesetId(0), 2),
ChildOf(layer),
TilePos::new(3, 4),
));
}
}
Other components (TileFlip, TileVisible, TileColor, …) get a default value, and the TiledMapReference is inserted from the parent layer.
If the tile has custom properties in its tileset, they are also inserted on the new entity.
Rules and Limitations
- A position holds a single tile, as in Tiled: spawning a tile, or moving a tile, onto a position already used by another tile of the same layer despawns this other tile, whatever its tileset.
- Layers cannot grow: tiles outside of the map bounds (see
TiledMapAsset::tilemap_size) are neither rendered nor used to compute physics colliders, and a warning is logged. - Tiles cannot change of layer: changing the
ChildOfof a tile is not supported. Despawn it and spawn a new one in the other layer instead. - Custom properties are not updated when you modify the
TiledTilecomponent of an existing tile. - A tileset which cannot be used in a tiles layer (for instance an images collection with images of different sizes) cannot be used for spawned tiles either.
Objects
Each object is an entity with a TiledObject component, describing its shape, child of its TiledLayer::Objects entity.
Its position is given by its Transform, relative to its layer.
When the TiledObject component changes, the object visual (for tile and text objects) and its physics colliders are spawned again.
When it is removed or when the object is despawned, they are despawned as well.
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
/// Turn all ellipses into rectangles
fn change_shapes(mut objects: Query<&mut TiledObject>) {
for mut object in objects.iter_mut() {
if let TiledObject::Ellipse { width, height } = *object {
*object = TiledObject::Rectangle { width, height };
}
}
}
/// Spawn a new rectangle object in the given objects layer
fn spawn_object(mut commands: Commands) {
let layer = Entity::PLACEHOLDER;
commands.spawn((
TiledObject::Rectangle {
width: 32.,
height: 16.,
},
TiledName("door".to_string()),
Transform::from_xyz(64., -32., 0.),
ChildOf(layer),
));
}
}
When spawning an object:
- give it a
TiledNameif you use physics settings filtering objects by name, - as for tiles, its
TiledMapReferenceis inserted from the parent layer, and aTiledObject::Tilegets the custom properties of its tile.
Moving an object (ie. modifying its Transform) does not need any update: its visual and colliders are its children and move along with it.
Images
An image layer has a single child holding a TiledImage component: the image handle, its position, size and repeat settings.
Its Sprite is derived from it: to change the image, modify the TiledImage component instead of the Sprite.
Without the render feature, the image is not loaded: TiledImage has no image handle and there is no Sprite.
Reacting to Changes
Map loading events (MapCreated, LayerCreated, TileWithPropertiesCreated, ObjectCreated) are only sent when a map is loaded, not when you modify it afterwards.
Two events are however sent when derived entities are spawned:
TiledEvent<TilemapCreated>, each time a tilemap is spawned: when the map is loaded, but also when a tile using a new tileset is added to a layer.TiledEvent<ColliderCreated>, each time a collider is spawned: since colliders are spawned again when their source changes, you receive this event every time a tiles layer or an object is modified.
For instance, if you add a RigidBody to colliders when receiving ColliderCreated (see the physics guide), new colliders will get it as well.
Entities spawned at runtime get a TiledMapReference to their map, so the TiledMapLayers, TiledMapTiles and TiledMapObjects system parameters list them along with the ones spawned with the map.
To find the tile at a given position of a layer, use the TiledTileLayerStorage component of this layer.
Respawning a Map Discards Modifications
All the modifications you made are lost when the map is respawned from its asset, which happens when:
- you insert the
RespawnTiledMapcomponent, - the map is hot-reloaded,
- you modify the
TiledMap,TilemapAnchor,TiledMapLayerZOffset,TilemapRenderSettingsorTiledPhysicsSettingscomponents of the map entity.
See Spawn / Despawn / Reload a Map for more information.
Performance
- Modifying tiles only updates the tiles which changed, and the tilemaps they belong to.
- However, physics colliders of a tiles layer are computed again as a whole whenever one of its tiles changes: on a layer with many tiles, it can take a significant amount of time. If you frequently modify a large tiles layer, consider keeping colliders out of it (see the physics settings to filter layers), or splitting it into several layers.
- Modifications are processed once per frame: modifying many tiles in the same frame costs much less than modifying them over several frames.
Add Physics Colliders
Tiled allows you to add objects to your map—either directly on an object layer or attached to a tile.
bevy_ecs_tiled can use these objects to automatically spawn physics colliders when loading the map.
Two physics engines are supported out of the box:
Both are well-integrated and offer similar features in the context of bevy_ecs_tiled. You can use them as-is, customize their behavior, or implement your own backend.
Creating Collider Objects in Tiled
To spawn colliders, you need to define objects in your map:
- Objects on an object layer: These are the standard objects you place in Tiled on an object layer.
- Objects attached to a tile: Edit your tileset and use Tiled’s built-in collision editor to define collision shapes for tiles.
Both types of objects are supported and will result in physics colliders being spawned in your game, based on their shapes.
Automatically Spawning Colliders
To automatically spawn colliders from Tiled objects, you need to:
- Enable the appropriate feature in your
Cargo.toml: Eitheravianorrapier, depending on your backend choice. You can also enable only thephysicsfeature and provide your own backend (see below).
Example: Using the Avian backend
[dependencies]
bevy = "0.20"
bevy_ecs_tiled = { version = "0.16", features = ["avian"] }
Note: You may need to adjust
bevyandbevy_ecs_tiledversions.
- Add the
TiledPhysicsPlugin<T>with theTiledPhysicsBackendof your choice.
Example: Using the Avian backend
use bevy::prelude::*;
use avian2d::prelude::*;
use bevy_ecs_tiled::prelude::*;
// You must enable the 'avian' feature for bevy_ecs_tiled
fn main() {
App::new()
// Load bevy_ecs_tiled main plugin
.add_plugins(TiledPlugin::default())
// Load bevy_ecs_tiled physics plugin (select Avian backend)
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default())
// Load Avian main plugin
.add_plugins(PhysicsPlugins::default().with_length_unit(100.0))
// Add your systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(TiledMap(asset_server.load("map.tmx")));
}
Colliders will be spawned for every object or tiles colliders in your map automatically.
Colliders are derived from the map entities: if you add, modify or remove a tile or an object after the map has been loaded, the corresponding colliders are automatically spawned again.
We provide two TiledPhysicsBackend that can be used out of the box:
TiledPhysicsAvianBackend: for the Avian 2D physics engineTiledPhysicsRapierBackend: for the Rapier 2D physics engine
Note: You can actually use several physics backends at the same time if you register the
TiledPhysicsPlugin<T>plugin multiple times, but with differentTiledPhysicsBackend.
Selecting Which Layers and Objects Get Colliders
By default, colliders are spawned for all tiles layers and objects.
To select which ones get colliders, use TiledColliderStrategy::Disabled, the same way as any other collider strategy:
- set it in
TiledPhysicsSettingsto disable colliders for the whole map, - insert it as a component on a layer or an object entity to disable colliders for this layer or object only,
- insert it as a component on a tile entity to exclude this tile from the colliders of its layer. On a tile, other strategies have no effect: the tile uses the strategy of its layer.
Since tiles inherit the custom properties of their tile in the tileset, adding a
TiledColliderStrategycustom property to a tile in the Tiled tileset editor (with theuser_propertiesfeature) excludes all the tiles of this kind.
An object uses its own strategy if it has one, otherwise the one of its layer, otherwise the one of the map. For instance, you can disable colliders for the whole map and enable them for a few layers or objects only, by inserting another strategy on them. Colliders are spawned again, or despawned, when this component is inserted, modified or removed.
Since it is a regular component, it can be set from Tiled using a custom property (see the custom properties guide), or inserted from an observer, for instance to select layers or objects by name:
Example: Only spawn colliders for certain layers and objects
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use avian2d::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands
.spawn((
TiledMap(asset_server.load("finite.tmx")),
// Do not create colliders by default...
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
collider_strategy: TiledColliderStrategy::Disabled,
..default()
},
))
// ... but create them for the layer named 'collision'
.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);
}
},
)
// ... and for the objects named 'hitbox'
.observe(
|object_created: On<TiledEvent<ObjectCreated>>,
objects_query: Query<&TiledName, With<TiledObject>>,
mut commands: Commands| {
let object = object_created.origin;
if objects_query.get(object).is_ok_and(|name| name.0 == "hitbox") {
commands.entity(object).insert(TiledColliderStrategy::Polyline);
}
},
);
}
}
The collision shapes of tiles, defined in the Tiled tileset editor, are not entities: to only use some of them, filter them by name using TiledPhysicsSettings::tile_shapes_filter.
It applies to the tiles of tiles layers as well as to tile objects:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use avian2d::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
TiledMap(asset_server.load("finite.tmx")),
// Only use the tiles collision shapes named 'collision'
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
tile_shapes_filter: TiledFilter::from(["collision"]),
..default()
},
));
}
}
Colliders Aggregation
Tiled uses simple shapes (rectangles, ellipses, polygons) to define colliders.
To reduce the number of physics colliders and improve performance, bevy_ecs_tiled tries to merge these simple shape colliders into a single complex one whenever possible.
- Tiles: Merging is actually performed at the tiles layer level.
Eventhough you can use several shapes to define a tile’s collider, these shape will be merged into a single collider and all tile colliders for a given tiles layer will also be merged together.
The collider is inserted on the tiles layer entity, and spawned again whenever a tile of this layer is added, modified (including its
TileFlip) or removed. Colliders of large layers can also be split in chunks. Tiles flips (horizontal, vertical and diagonal) are applied to their collider, the same way they are applied to their rendering. - Regular objects: If an object references a tile, it will inherit that tile’s collider and if the tile has several shapes, they will be merged. The collider is inserted on the object entity and each object always gets its own collider.
The first collider of a tiles layer or an object is inserted on the layer or object entity itself, so you can directly add other physics components to it. If there are several colliders (see below), the next ones are spawned as children of this entity.
Collider Strategy
The TiledColliderStrategy selects how physics colliders are created from Tiled shapes:
Polyline(default): a single collider made of all the segments outlining the shapes. Bodies can end up inside of the shape.Triangulation: shapes are triangulated and all triangles are aggregated in a single “solid” compound collider.LineStrip: one collider for each ring outlining the shapes, so there can be several colliders.Disabled: no collider at all (see above).
The strategy is set for the whole map, in TiledPhysicsSettings:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
TiledMap(asset_server.load("map.tmx")),
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
collider_strategy: TiledColliderStrategy::Triangulation,
..default()
},
));
}
}
It can be overridden for a given layer or object: TiledColliderStrategy is also a component, which you can insert on a layer or an object entity.
An object uses its own strategy if it has one, otherwise the one of its layer, otherwise the one of the map.
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
// Use line strips for the tiles layer named "walls"
fn on_layer_created(
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 == "walls") {
commands.entity(layer).insert(TiledColliderStrategy::LineStrip);
}
}
}
Colliders are spawned again when this component is inserted, modified or removed.
With the user_properties feature, you can also directly add it from Tiled as a custom property of the layer or object.
Colliders Chunks
By default, all the tiles of a layer are merged in a single set of colliders. This is the best option for maps which are not modified once loaded, but it means that all the colliders of the layer are computed again whenever one of its tiles is added, modified or removed, which can take a while on large maps.
If you modify your maps at runtime, you can split the colliders of tiles layers in chunks: each chunk of tiles gets its own colliders and only the chunks whose tiles are modified are computed again.
The chunk size, in tiles, is set for all the tiles layers of the map in TiledPhysicsSettings:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
TiledMap(asset_server.load("map.tmx")),
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
// Split tiles layers colliders in chunks of 32x32 tiles
tiles_chunk_size: TiledColliderChunkSize::Size(UVec2::splat(32)),
..default()
},
));
}
}
It can be overridden for a given tiles layer by inserting a TiledColliderChunkSize component on the layer entity, either to use another size or to disable chunking for this layer (TiledColliderChunkSize::Disabled).
You can also only use this component, to enable chunking for a single layer of the map:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn on_layer_created(
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 == "destructible") {
commands
.entity(layer)
.insert(TiledColliderChunkSize::Size(UVec2::splat(16)));
}
}
}
When chunking is enabled for a layer:
- the layer entity does not hold any collider. Each chunk with at least one collider has its own
TiledColliderChunkentity, child of the layer, holding the collider of the chunk; - colliders are not merged across chunks: two adjacent tiles which are not in the same chunk have separate colliders. With the
PolylineandLineStripstrategies, the edges shared by two chunks are not part of their colliders, so the outline of the layer is the same than without chunks. With theTriangulationstrategy, each chunk is a separate solid; - a chunk boundary is still a junction between two colliders: depending on your physics engine, a body with a flat side (eg. a box) sliding over it can catch on the first vertex of the next collider (“ghost collision”). Give such bodies rounded corners, for instance using a
CollisionMarginwith Avian, or use larger chunks; - smaller chunks make updates faster, but produce more colliders.
With the debug feature, the TiledDebugColliderChunksPlugin displays the bounding box of each chunk colliders.
Custom Physics Backends
For advanced use cases, you can implement your own physics backend.
Just create a struct that implements the TiledPhysicsBackend trait, and use it when registering the TiledPhysicsPlugin<T> plugin.
A backend only has to create colliders out of a geometry: it declares the component(s) making a collider (the Collider associated type) and provides a colliders() function returning them for a given geometry and TiledColliderStrategy.
bevy_ecs_tiled takes care of inserting these colliders on the right entities and of removing them when their source changes.
The collider_shapes() helper converts a geometry into simple shapes (polylines or triangles) according to the requested strategy.
The geometry is a TiledColliderGeometry: besides its polygons, it holds the geometry of the adjacent colliders chunks, if any. Colliders made of segments should be built from its outline(), which does not include the edges shared with these chunks.
See this example for more information.
Physics Events
When a collider entity is spawned, a TiledEvent<ColliderCreated> event is sent.
Since colliders are spawned again when their source changes, you can receive this event several times for the same tiles layer or object.
It contains information about the origin of the collider.
This event is sent for each collider: a tiles layer or an object can have several colliders (for instance with TiledColliderStrategy::LineStrip or collider chunks), held by its entity or by its descendants.
The event origin is the entity holding the collider, while source_entity() is the tiles layer or object it is created for.
This can be useful to add custom components to your colliders. For instance, with Avian:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use avian2d::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands
.spawn(TiledMap(asset_server.load("map.tmx")))
.observe(|collider_created: On<TiledEvent<ColliderCreated>>, mut commands: Commands| {
// Filter collider created from Tiled objects
if collider_created.event().event.source == TiledColliderSource::Object {
// Add a RigidBody::Static to the object: insert it on the source entity rather than on
// each collider entity, so all the colliders of the object belong to a single rigid body
commands
.entity(collider_created.source_entity())
.insert(RigidBody::Static);
}
});
}
}
Using Tiled Custom Properties
Tiled allows you to add “custom properties” to various items such as layers, tiles, objects, or maps.
These custom properties can be:
- Standard types: string, integer, float, color, etc.
- Custom types: your own structures with sub-properties (which can themselves be standard or custom types)
With bevy_ecs_tiled, you can load these custom properties into your game and access them as regular Bevy Component or Resource.
This means you can define game logic directly in the Tiled editor and use it seamlessly in your Bevy game.
For example, you could:
- Associate a “movement cost” with a tile type
- Create an object representing your player or an enemy
- Add a generic “trigger zone” (e.g., damaging zone, victory zone)
- …or anything else your game needs!
Note: Even without the
user_propertiesfeature, the class and custom properties of the map, layers and objects are available as raw Tiled data in theirTiledPropertiescomponent. Tiles properties can be retrieved from their tileset, usingTiledMapAsset::tile().
Overview
The user properties mechanism relies on Bevy’s reflection system.
To use custom properties from Tiled in your game, you need to:
- Enable the
user_propertiesfeature in your localCargo.tomlfile. - Declare your custom types in Rust and make them reflectable.
- Run your game once to export these types as a
.jsonfile, readable by Tiled. - Import this
.jsonfile into the Tiled editor to make your types available as custom properties.
Once this is done, you can use your types directly in Tiled. When you load your map, the corresponding Component or Resource will be automatically inserted into your Bevy world.
For a quick demonstration, see the dedicated example.
Enabling the feature
Update your local Cargo.toml file to enable the user_properties feature:
[dependencies]
bevy = "0.20"
bevy_ecs_tiled = { version = "0.16", features = ["user_properties"] }
Note: You may need to adjust
bevyandbevy_ecs_tiledversions.
Declaring Types for Custom Properties
Each Tiled map, layer, tile, or object is represented by a Bevy Entity.
If you want to add custom properties to them, these properties should be a Component.
To make your custom types usable in Tiled, they must be “reflectable”:
- Derive the
Reflecttrait for your type. - Register your type with Bevy.
Example:
use bevy::prelude::*;
// Declare a component and make it reflectable
#[derive(Component, Reflect, Default)]
#[reflect(Component, Default)]
struct Biome {
block_line_of_sight: bool,
ty: BiomeType,
}
// Any sub-type must also be reflectable, but does not need to be a Component
#[derive(Default, Reflect)]
#[reflect(Default)]
enum BiomeType {
#[default]
Unknown,
Forest,
Plain,
Mountain,
Desert,
}
// Register your top-level struct in the Bevy registry
fn main() {
App::new()
.register_type::<Biome>();
}
Tip:
Deriving Default is useful: you don’t have to fill all fields in Tiled; missing fields will use the type’s default value.
Importing Custom Properties into Tiled
Before you can add custom properties in Tiled, you need to export them from your app and import them into Tiled.
With the user_properties feature, your app can produce, at startup, a .json export of all the types registered with Bevy.
Export is disabled by default: set the path of the export file on the TiledPlugin:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
App::new().add_plugins(TiledPlugin {
types_export_file: Some("tiled_types_export.json".into()),
// Only export the types of your game
types_filter: TiledFilter::from(bevy_ecs_tiled::regex::RegexSet::new([r"^my_game::.*"]).unwrap()),
});
}
To import this file in Tiled:
- In Tiled, go to View → Custom Types Editor
- Click the Import button and select your
.jsonfile - You will now see all custom types imported from your application
Adding Custom Properties in Tiled
Once imported, you can add custom properties to your map:
- Select the element (map, layer, object, etc.) you want to add a property to.
- In the “Custom Properties” panel, right-click and select Add Property
- Choose the type you want to add and give it a name.
- For example, add the
BiomeInfostype from the earlier example: - Set the values as needed for this element.
When you load the map, the corresponding Bevy entity will have the appropriate Component with the values you set.
Tile Properties
Properties added to a tile in a tileset are inserted on every entity referencing this tile:
- the tiles using it in tiles layers,
- the tile objects using it. If the object also has its own properties, they take precedence over the tile ones.
This also applies to tiles and tile objects you spawn after the map has been loaded: tile properties are inserted during TiledPostUpdateSystems::SyncTiles.
Note that modifying the TiledTile component (tileset ID or tile ID) of an existing tile does not update its properties.
Since Tiled object IDs are not known anymore once the map has been loaded, object references in these properties cannot be resolved: they are set to Entity::PLACEHOLDER.
When loading a map, all custom properties are inserted before the map events (MapCreated, LayerCreated, …) are sent.
Note: Only add properties imported from Bevy. Properties created only in Tiled (ie. not exported from your app) will not be loaded in Bevy. You can also control which properties are exported from your application using
TiledPlugin::types_filter.
Custom Properties Usage with Bevy
When loading a Tiled map with custom properties, a common pattern is to use Bevy On<Add> observers to react to the spawn of a particular Tiled element.
When the On<Add> observer is triggered, you can then insert additional components or spawn another entity.
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
// Declare a marker component: assume it will be added to a particular Tiled object
#[derive(Component, Default, Debug, Reflect)]
#[reflect(Component, Default)]
struct PlayerSpawn;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands
.spawn(TiledMap(asset_server.load("map.tmx")))
// We will run this observer for every Tiled object with the `PlayerSpawn` component
.observe(|add_player_spawn: On<Add, PlayerSpawn>, mut commands: Commands| {
// Retrieve the Tiled object entity
let player_spawn_entity = add_player_spawn.event().entity;
// Add extra components
commands
.entity(player_spawn_entity)
.insert((
...
));
});
}
}
You can also have a look to the dedicated example.
Special Considerations
- You can add custom properties to objects, layers, or the map itself. To add properties to tiles, edit the tileset directly. We currently do not support adding properties to the tileset itself.
- For more on adding custom properties, see the official Tiled documentation.
- You can also add
Resources to your map. Since resources are global and not attached to a specific entity, they are only supported as map-level properties. If you add a resource to another Tiled element, it will be ignored.
Debug your project
Logging
Bevy uses the tracing crate for logging, which is very powerful for debugging and profiling.
You can find more information in the official documentation.
To get detailed information about what’s happening in your app, set the RUST_LOG environment variable to trace:
RUST_LOG=trace cargo run
This will show all logs at the trace level, but it can be very verbose.
To filter logs and only display information from bevy_ecs_tiled, use:
RUST_LOG=bevy_ecs_tiled=trace cargo run
This will only display logs from the bevy_ecs_tiled crate at the trace level.
bevy_ecs_tiled Debug Plugins
When the debug feature is enabled, bevy_ecs_tiled provides several debug plugins to help visualize and inspect your maps.
You can enable all debug plugins at once by adding the TiledDebugPluginGroup to your app:
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledDebugPluginGroup)
.run();
}
Or add them individually as needed:
TiledDebugObjectsPlugin: outline and position of each Tiled object;TiledDebugTilesPlugin:bevy_ecs_tilemapindex (TilePos) of each tile;TiledDebugMapAabbPlugin: axis-aligned bounding box (AABB) of each map;TiledDebugWorldStreamingPlugin: maps boundaries and streaming area of each world (requires theworldfeature);TiledDebugColliderChunksPlugin: bounding box of each physics collider chunk of tiles layers (requires thephysicsfeature, see the physics guide);TiledDebugAxisPlugin: axes at the world origin;TiledDebugTogglePlugin: toggle all debug gizmos using a keyboard key.
Most plugins take a configuration, which is inserted as a Resource: you can also update it at runtime.
Objects
The TiledDebugObjectsPlugin draws, for each object, its outline and an arrow pointing to its position (ie. its Transform).
Colors are cycled from a list, so neighbor objects can be told apart.
It is useful to check objects placement, for instance on isometric maps or after a rotation.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledDebugObjectsPlugin(TiledDebugObjectsConfig {
// Draw all objects in white, with a longer arrow
objects_colors_list: vec![Color::WHITE],
arrow_length: Vec2::new(-30., 30.),
}))
.run();
}
Tiles
The TiledDebugTilesPlugin draws the TilePos of each tile above it.
Note that bevy_ecs_tilemap origin is the bottom-left tile and its Y axis points up, whereas Tiled origin is the top-left tile.
On maps with small tiles, indexes may overlap and become hard to read: reduce the text size using TiledDebugTilesConfig.
Since text gizmos are drawn using lines, you can also reduce the lines width of the TiledDebugGizmos group (see below):
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledDebugTilesPlugin(TiledDebugTilesConfig {
text_size: 5.,
..default()
}))
.add_systems(Startup, |mut config_store: ResMut<GizmoConfigStore>| {
config_store.config_mut::<TiledDebugGizmos>().0.line.width = 1.;
})
.run();
}
Note: One text is drawn per tile, every frame: on large maps, this plugin can be expensive.
Map bounding boxes
The TiledDebugMapAabbPlugin draws two rectangles for each map:
- in orange, the AABB of the tiles grid as computed by
bevy_ecs_tilemap(ie. where tiles are actually rendered); - in aqua, the AABB obtained by converting the map corners from Tiled coordinates to world space.
Both rectangles should overlap, whatever the map orientation or TilemapAnchor.
If they do not, there is probably an issue with coordinates conversion: objects and image layers may not be positioned where you expect them.
This plugin is especially useful when checking map placement and anchoring.
Note: For infinite maps, the AABB only covers the chunks containing tiles: objects located outside of these chunks will lie outside of the AABB.
You can change the colors, or hide one of the rectangles by setting its color to None, using the TiledDebugMapAabbConfig:
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledDebugMapAabbPlugin(TiledDebugMapAabbConfig {
// Only display the AABB computed from Tiled coordinates
tilemap_aabb_color: None,
tiled_aabb_color: Some(Color::WHITE),
}))
.run();
}
World streaming
The TiledDebugWorldStreamingPlugin draws, for each world:
- a rectangle around each map of the world, colors being cycled from a list;
- if
TiledWorldStreamingis set, a red rectangle centered on the camera: maps overlapping this area are spawned, the others are despawned.
It helps tuning the streaming area and checking maps alignment within a world.
Set streaming_area_color to None or maps_colors_list to an empty list in TiledDebugWorldStreamingConfig to hide one or the other.
Axis
The TiledDebugAxisPlugin draws the X (red) and Y (green) axes at the world origin.
It does not have any configuration: use it as a reference when positioning maps, worlds or anchors.
Toggle and configure debug gizmos
All debug plugins draw their gizmos using the TiledDebugGizmos gizmo config group.
When this group is disabled, debug gizmos are hidden and debug systems do not run at all.
The easiest way to toggle debug gizmos is to choose a keyboard key for the TiledDebugTogglePlugin, which is part of TiledDebugPluginGroup but does not use any key by default:
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledDebugPluginGroup.set(TiledDebugTogglePlugin {
key: Some(KeyCode::F2),
}))
.run();
}
If you add debug plugins individually, add TiledDebugTogglePlugin as well.
You can also configure debug gizmos (enabled, lines width, render layers…) from your own systems using the GizmoConfigStore resource, and use the tiled_debug_gizmos_enabled run condition for your own debug systems:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn hide_debug_gizmos(mut config_store: ResMut<GizmoConfigStore>) {
let (config, _) = config_store.config_mut::<TiledDebugGizmos>();
config.enabled = false;
}
}
For more details, see the API reference.
Third-Party Debugging Tools
bevy-inspector-egui
This plugin is highly recommended for debugging and inspecting your game world.
Add the dependency to your Cargo.toml:
[dependencies]
bevy-inspector-egui = "0.30"
Then add the WorldInspectorPlugin to your application:
use bevy::prelude::*;
use bevy_inspector_egui::quick::WorldInspectorPlugin;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(EguiPlugin { enable_multipass_for_primary_context: true })
.add_plugins(WorldInspectorPlugin::new())
.run();
}
Now, you can browse and edit components from all entities spawned in your game in real time.
More information is available on the project’s GitHub page.
Physics Plugins
Both Avian and Rapier provide their own debug visualization plugins, which are invaluable when working with colliders and physics.
Avian Physics Debugging:
use bevy::prelude::*;
use avian2d::prelude::*;
fn main() {
App::new()
// Add Avian regular plugin
.add_plugins(PhysicsPlugins::default().with_length_unit(100.0))
// Add Avian debug plugin
.add_plugins(PhysicsDebugPlugin::default())
.run();
}
Rapier Physics Debugging:
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
fn main() {
App::new()
// Add Rapier regular plugin
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(100.0))
// Add Rapier debug plugin
.add_plugins(RapierDebugRenderPlugin::default())
.run();
}
Note: For Rapier, you must enable either the
debug-render-2dfeature on thebevy_rapier2dcrate or therapier_debugfeature onbevy_ecs_tiled.
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 themap_dynamicexample. - 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
TiledColliderStrategyreplaces both the backends variants and the name filters ofTiledPhysicsSettings. 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,geoandregexcrates are re-exported at the crate root:use bevy_ecs_tiled::{tiled, geo, regex};instead ofbevy_ecs_tiled::prelude::{tiled, geo, regex}, collider_shapes(),multi_polygon_as_line_strings(),multi_polygon_as_triangles()andTiledColliderShape, 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:
| Before | After |
|---|---|
tiled::TiledPlugin | TiledPlugin (crate root) |
tiled::sets::* | sets::* |
tiled::map::asset::TiledMapAsset | asset::map::TiledMapAsset |
tiled::map::loader::TiledMapLoaderError | asset::map::TiledMapLoaderError |
tiled::world::asset::TiledWorldAsset | asset::world::TiledWorldAsset |
tiled::world::loader::TiledWorldLoaderError | asset::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::TiledAnimation | render::animation::TiledAnimation |
tiled::tile::TiledTilemap | render::tilemap::TiledTilemap |
tiled::object::{TiledObjectVisualOf, TiledObjectVisuals, TiledObjectTextBox, TiledObjectText} | render::object::* |
tiled::properties::export_types | properties::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*Createdevents, - 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:
| Removed | Replacement |
|---|---|
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.
| Type | ID | Main APIs |
|---|---|---|
TilesetId | tileset of a map | TiledTile, TiledTilemap, TiledObject::Tile, TiledEvent::tilemap_tileset_id(), TiledMapAsset::tileset(), TiledMapAsset::tile() |
LayerId | Tiled layer ID | TiledMapAsset::layer() |
ObjectId | Tiled object ID | TiledMapAsset::object() |
WorldMapId | index of a map in its .world file | TiledWorldReference, 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:
| Before | After |
|---|---|
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
TileCreatedhas been renamedTileWithPropertiesCreated: as before, it is only sent for tiles with custom properties, when the map is loaded. It no longer holds tilemap information:tilemap_entity()andtilemap_tileset_id()returnNone, usetile_tileset_id()instead.TiledEventcan no longer be built nor sent from outside the crate:new(),transmute(),with_*()andsend()are now private. If you sent your ownTiledEvents, define your own event type instead.- The type parameter of
TiledEvent<E>is bound by the new sealedTiledEventKindtrait: replaceE: Debug + Clone + Copy + ReflectbyE: TiledEventKindin your generic code. TiledEventis no longer aComponent.
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:
| Removed | Replacement |
|---|---|
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 theTiledTileinstead of its size, and returns anOption<Vec2>(Noneif the tile does not exist in the map). You can also use the newTiledMapHelpersystem parameter, which only needs the tile entity:maps.tile_relative_position(tile_entity).TiledLayerParallax::parallax_xandparallax_yare merged intoparallax: Vec2.TiledObject::kind()has been removed:TiledObjectimplementsDisplayinstead (format!("{object}")).TiledObject::center(),vertices(),line_string()andpolygon()are no longer public: useTiledMapAsset::object_center(),object_vertices(),object_line_string()andobject_polygon(), which only need the object and itsGlobalTransform.TiledObject::Text::font_sizeis now af32.TiledObject::from_object_data()now takes theTiledMapAssetas first argument.TiledObjectVisualOfno longer requires aSprite, and is also inserted on theTiledObjectTextBoxof text objects: do not assume that a visual entity has aSprite.TiledName::matches()has been removed: usefilter.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:
| Removed | Replacement |
|---|---|
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::HandleWorldChunkingis nowHandleWorldStreaming,TiledDebugWorldChunkPluginandTiledDebugWorldChunkConfigare nowTiledDebugWorldStreamingPluginandTiledDebugWorldStreamingConfig, whoseworld_chunk_colorfield is nowstreaming_area_color,- the
world_chunkingexample is nowworld_streaming.
If you set TiledWorldChunking from Tiled custom properties, export your types again and use TiledWorldStreaming instead.
9. Physics
TiledPreUpdateSystems::SpawnPhysicsCollidershas been removed: useTiledPostUpdateSystems::SyncPhysics.- Colliders are spawned again when their source changes: you can receive
TiledEvent<ColliderCreated>several times for the same source. - Modifying
TiledPhysicsSettingsno longer respawns the map or the world: only physics colliders are spawned again. TiledEvent<ColliderCreated>::tiles()has been removed: query theTiledTilechildren of the layer instead (TiledTile,TilePos,TileFlip).ColliderCreated::collider_ofandColliderCreated::new()have been removed: the event origin is the collider entity. UseTiledEvent::source_entity(), or theTiledColliderOfcomponent 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: usegeo::unary_unionto merge polygons. TheTiledPhysicsSettings::simplify_geometrysetting 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:
| Before | After |
|---|---|
objects_layer_filter | Insert TiledColliderStrategy::Disabled on the objects layers which should not get colliders |
objects_filter | Insert TiledColliderStrategy::Disabled on the objects which should not get colliders |
tiles_layer_filter | Insert TiledColliderStrategy::Disabled on the tiles layers which should not get colliders |
tiles_objects_filter | Renamed 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
TiledColliderChunkentity, child of the layer. - Additional colliders (
TiledColliderStrategy::LineStrip, or geometry simplification disabled) are children of this entity, namedTiledCollider(<index>)instead ofAvian[...]/Rapier[...]. They now also have theTiledColliderOf,TiledColliderSourceandTiledColliderPolygonscomponents, and aTiledEvent<ColliderCreated>is sent for each of them. TiledColliderPolygonsholds 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: itspolygonsreplace the formerMultiPolygon, and itsoutline()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 intoTiledColliderShapes according to the requested strategy. - If you need access to the
Worldto build your collider (eg. to add an asset), use component hooks or observers on your collider component: see thephysics_customexample. multi_polygon_as_line_strings()now returns an iterator over borrowed line strings instead of aVec.
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:
| Before | After |
|---|---|
map_reference.0 | map_reference.entity() or *map_reference |
animation.frames (TiledAnimation) | animation.frames() |
TiledAnimation::current_frame and timer are internal state and are no longer accessible.
Resources
Migration to bevy_ecs_tiled v0.15
This guide outlines the steps required to migrate your project to version 0.15 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
- API cleanup: the
get_prefix is dropped fromTiledEventaccessors,TiledMapStorage/TiledWorldStoragelookups and map helper functions, following Rust API guidelines - Storage iterators now return opaque iterators yielding owned values
- Typed loader errors: unsupported orientations and Tiled parsing errors are reported as dedicated error variants instead of panicking or being converted to
std::io::Error - No more panics when exporting Tiled types or reading invalid user properties
- Isometric and hexagonal maps had multiple fixes and should now be positioned like in Tiled
- New debug plugin
TiledDebugMapAabbPluginto display maps bounding boxes
Migration Steps
1. Update Dependencies
bevy = "0.20"
bevy_ecs_tiled = "0.15"
2. Drop the get_ Prefix from Accessors
All getters lose their get_ prefix, their signatures being otherwise unchanged.
In most cases, removing get_ from the method name is all you need to do.
TiledEvent accessors
| Before (v0.14) | After (v0.15) |
|---|---|
get_world_entity() | world_entity() |
get_world_asset() | world_asset() |
get_world() | world() |
get_map_entity() | map_entity() |
get_map_asset() | map_asset() |
get_map() | map() |
get_layer_entity() | layer_entity() |
get_layer_id() | layer_id() |
get_layer() | layer() |
get_tilemap_entity() | tilemap_entity() |
get_tilemap_tileset_id() | tilemap_tileset_id() |
get_tilemap_tileset() | tilemap_tileset() |
get_tile_entity() | tile_entity() |
get_tile_pos() | tile_pos() |
get_tile_id() | tile_id() |
get_tile() | tile() |
get_object_entity() | object_entity() |
get_object_id() | object_id() |
get_object() | object() |
TiledEvent<ColliderCreated>::get_tiles() is also renamed to TiledEvent<ColliderCreated>::tiles().
TiledMapStorage and TiledWorldStorage lookups
| Before (v0.14) | After (v0.15) |
|---|---|
TiledMapStorage::get_layer_entity() | TiledMapStorage::layer_entity() |
TiledMapStorage::get_layer_id() | TiledMapStorage::layer_id() |
TiledMapStorage::get_layer() | TiledMapStorage::layer() |
TiledMapStorage::get_tile_entities() | TiledMapStorage::tile_entities() |
TiledMapStorage::get_tile_id() | TiledMapStorage::tile_id() |
TiledMapStorage::get_tile() | TiledMapStorage::tile() |
TiledMapStorage::get_object_entity() | TiledMapStorage::object_entity() |
TiledMapStorage::get_object_id() | TiledMapStorage::object_id() |
TiledMapStorage::get_object() | TiledMapStorage::object() |
TiledWorldStorage::get_map_entity() | TiledWorldStorage::map_entity() |
TiledWorldStorage::get_map_id() | TiledWorldStorage::map_id() |
Helper functions
| Before (v0.14) | After (v0.15) |
|---|---|
get_layer_from_map() | layer_from_map() |
get_tileset_from_map() | tileset_from_map() |
get_tile_from_map() | tile_from_map() |
get_object_from_map() | object_from_map() |
Before (v0.14):
#![allow(unused)]
fn main() {
fn on_object_created(
object_created: On<TiledEvent<ObjectCreated>>,
assets: Res<Assets<TiledMapAsset>>,
) {
let Some(object) = object_created.event().get_object(&assets) else {
return;
};
// ...
}
}
After (v0.15):
#![allow(unused)]
fn main() {
fn on_object_created(
object_created: On<TiledEvent<ObjectCreated>>,
assets: Res<Assets<TiledMapAsset>>,
) {
let Some(object) = object_created.event().object(&assets) else {
return;
};
// ...
}
}
3. Update TiledMapStorage and TiledWorldStorage Usage
Iterators
layers(), objects(), tiles() and maps() no longer expose the inner HashMap iterator: they return an impl Iterator yielding owned IDs and entities (and a &[Entity] slice for tiles).
Before (v0.14):
#![allow(unused)]
fn main() {
for (id, entity) in storage.objects() {
// `id: &u32`, `entity: &Entity`
let entity = *entity;
}
}
After (v0.15):
#![allow(unused)]
fn main() {
for (id, entity) in storage.objects() {
// `id: u32`, `entity: Entity`
}
}
Remove any now unneeded dereference (*id, *entity) or .copied() / .cloned() call.
If you relied on HashMap iterator specific methods (eg. len()), use the generic Iterator API instead (eg. count()).
Tile entities
TiledMapStorage::tile_entities() (formerly get_tile_entities()) now returns a &[Entity] instead of a cloned Vec<Entity>.
Call .to_vec() if you really need an owned value.
clear() is no longer public
TiledMapStorage::clear() and TiledWorldStorage::clear() have been removed from the public API.
To respawn a map or a world, insert the RespawnTiledMap or RespawnTiledWorld component instead:
#![allow(unused)]
fn main() {
commands.entity(map_entity).insert(RespawnTiledMap);
}
4. Handle New Loader Errors
TiledMapLoaderError and TiledWorldLoaderError changed:
- Tiled parsing errors are now reported as a new
Tiledvariant, holding the originaltiled::Error, instead of being converted tostd::io::Error(ie. theIovariant). - Maps with an unsupported orientation (staggered or oblique) now fail to load with
TiledMapLoaderError::UnsupportedOrientationinstead of panicking during spawn. - Both enums are now
#[non_exhaustive]: if youmatchon them, add a wildcard arm.
#![allow(unused)]
fn main() {
match error {
TiledMapLoaderError::Io(e) => error!("I/O error: {e}"),
TiledMapLoaderError::Tiled(e) => error!("Invalid Tiled map: {e}"),
TiledMapLoaderError::UnsupportedOrientation(o) => error!("Unsupported orientation: {o:?}"),
_ => error!("Failed to load map: {error}"),
}
}
A non-panicking try_tilemap_type_from_map() helper is also available, returning None for unsupported orientations.
6. Handle export_types() Result
If you call export_types() directly, it now returns a std::io::Result<()> instead of panicking:
#![allow(unused)]
fn main() {
if let Err(e) = export_types(®istry, "tiled_types.json", &TiledFilter::All) {
error!("Failed to export Tiled types: {e}");
}
}
When types export is configured through the plugin (TiledPluginConfig::tiled_types_export_file), a failure now logs an error instead of crashing the application.
Resources
Migration to bevy_ecs_tiled v0.14
This guide outlines the steps required to migrate your project to version 0.14 of bevy_ecs_tiled.
Main Changes
- Bevy v0.20 Support:
bevy_ecs_tilednow works seamlessly with Bevy v0.20, allowing you to take advantage of the latest engine features and performance improvements. See the Bevy 0.20 release notes for details.
Migration Steps
-
Update Dependencies in
Cargo.toml:bevy = "0.20" bevy_ecs_tiled = "0.14"Note: You may also need to update other Bevy-related crates to ensure compatibility.
-
Review the Bevy Migration Guide: Follow Bevy’s official migration steps to update your project from Bevy v0.19. This will help you resolve breaking changes and take advantage of new features.
Resources
Migration to bevy_ecs_tiled v0.13
This guide outlines the steps required to migrate your project to version 0.13 of bevy_ecs_tiled.
Main Changes
- Bevy v0.19 Support:
bevy_ecs_tilednow works seamlessly with Bevy v0.19, allowing you to take advantage of the latest engine features and performance improvements. See the Bevy 0.19 release notes for details.
Migration Steps
-
Update Dependencies in
Cargo.toml:bevy = "0.19" bevy_ecs_tiled = "0.13"Note: You may also need to update other Bevy-related crates to ensure compatibility.
-
Review the Bevy Migration Guide: Follow Bevy’s official migration steps to update your project from Bevy v0.18. This will help you resolve breaking changes and take advantage of new features.
Resources
Migration to bevy_ecs_tiled v0.12
This guide outlines the steps required to migrate your project to version 0.12 of bevy_ecs_tiled.
Main Changes
TiledAnimationAPI redesign for non-consecutive frame support- Physics colliders spawning rework with simplified geometry control
- Support for Text Objects and Group Layer
Migration Steps
1. Update Dependencies
Update your Cargo.toml to use version 0.12 and compatible physics backends:
bevy = "0.18"
bevy_ecs_tiled = "0.12"
avian2d = "0.6" # if using Avian physics
bevy_rapier2d = "0.34" # if using Rapier physics
2. Update TiledAnimation Usage
The animation API has been completely redesigned to support non-consecutive frame IDs and per-frame durations:
Before (v0.11):
#![allow(unused)]
fn main() {
pub struct TiledAnimation {
pub start: usize,
pub end: usize,
pub frame_duration: f32,
}
}
After (v0.12):
#![allow(unused)]
fn main() {
pub struct TiledAnimation {
pub frames: Vec<(usize, f32)>, // (atlas_index, duration_in_seconds)
pub current_frame: usize,
}
}
Impact: Update any code that creates or manipulates TiledAnimation components to use the new frames vector format. Each tuple contains the atlas frame index and its duration in seconds.
Important: Tile-layer animations via
bevy_ecs_tilemap::AnimatedTilestill require consecutive IDs and uniform durations. Violations will now emit warnings instead of silently dropping frames.
3. Update Physics Colliders Spawning
Physics collider handling has been significantly reworked. This change should allow to better handle most physics use cases (for instance #169)
Key Changes:
- One event per object: Only a single
ColliderCreatedevent is sent per physics object, not per collider - Backend control: Physics backends now decide the ECS hierarchy structure (colliders may be directly attached to the physics object rather than as child entities)
- Geometry simplification control: Two new options for controlling collider aggregation:
- Global setting:
TiledPhysicsSettings::<T>::simplify_geometry - Per-item override:
TiledPhysicsDisableGeometrySimplificationcomponent
- Global setting:
Update your physics event handlers:
#![allow(unused)]
fn main() {
// Old: Could receive multiple ColliderCreated events per object
fn on_collider_created(mut events: EventReader<ColliderCreated>) {
for event in events.read() {
// Handle each collider individually
}
}
// New: Single event per object, check the collider structure in physics backend
fn on_collider_created(mut events: EventReader<ColliderCreated>) {
for event in events.read() {
// Event now provides direct reference to parent entity
let parent = event.parent_entity;
}
}
}
Disable geometry simplification per-object when needed:
#![allow(unused)]
fn main() {
// Prevent merging colliders for a specific object
commands.entity(object_entity)
.insert(TiledPhysicsDisableGeometrySimplification);
}
4. Support for Text Objects and Group Layers (Optional)
Version 0.12 adds support for text objects and group layers:
- Text objects: Tiled text objects are now spawned with
TiledObjectTextandTiledObjectTextBoxcomponents - Group layers: Hierarchical layer organization is now fully supported. Use
get_layer_from_map()andget_object_from_map()helpers which now traverse group layers
No migration action required unless you’re explicitly working with these features.
Resources
Migration to bevy_ecs_tiled v0.11
This guide outlines the steps required to migrate your project to version 0.11 of bevy_ecs_tiled.
Main Changes
- Bevy v0.18 Support:
bevy_ecs_tilednow works seamlessly with Bevy v0.18, allowing you to take advantage of the latest engine features and performance improvements. See the Bevy 0.18 release notes for details.
Migration Steps
-
Update Dependencies in
Cargo.toml:bevy = "0.18" bevy_ecs_tiled = "0.11"Note: You may also need to update other Bevy-related crates to ensure compatibility.
-
Review the Bevy Migration Guide: Follow Bevy’s official migration steps to update your project for Bevy v0.18. This will help you resolve breaking changes and take advantage of new features.
Resources
Migration to bevy_ecs_tiled v0.10
This guide outlines the steps required to migrate your project to version 0.10 of bevy_ecs_tiled.
Main Changes
-
Bevy v0.17 Support:
bevy_ecs_tilednow works seamlessly with Bevy v0.17, allowing you to take advantage of the latest engine features and performance improvements. See the Bevy 0.17 release notes for details. -
Enhanced ColliderCreated Event: The
ColliderCreatedevent now includes a direct reference to the collider’s parent entity, making it easier to attach additional physics components or interact with spawned colliders. The event previously only contained aTiledColliderOrigin, which has been renamed toTiledColliderSource. -
External Type Re-exports: Types from external crates (such as
rs-tiled,geo, andregex) are now re-exported through dedicated modules. This avoids name clashes and makes type usage explicit.
Migration Steps
-
Update Dependencies in
Cargo.toml:bevy = "0.17" bevy_ecs_tiled = "0.10"Note: You may also need to update other Bevy-related crates to ensure compatibility.
-
Review the Bevy Migration Guide: Follow Bevy’s official migration steps to update your project for Bevy v0.17. This will help you resolve breaking changes and take advantage of new features.
-
Update Usage of External Types:
If your code uses types from
rs-tiled,geo, orregex, you must now reference them via their dedicated modules. This ensures clarity and prevents naming conflicts.#![allow(unused)] fn main() { use bevy_ecs_tiled::prelude::*; // For external types, use their module: let tiled_id: tiled::TiledId = 10; } -
Update Usage of
TiledEvent<ColliderCreated>:In previous versions, the event only provided a
TiledColliderOrigin. In v0.10, this has been renamed toTiledColliderSource, and the event now also includes a reference to the collider’s parent entity. This change makes it easier to interact with colliders and attach additional physics components directly after creation.
Resources
Migration to bevy_ecs_tiled v0.9
This guide outlines the steps required to migrate your project to version 0.9 of bevy_ecs_tiled.
Main Changes
- Improved Isometric Map Support:
Isometric maps are now much better supported, including correct physics collider shapes and placement. - Accurate Physics Colliders for Isometric Maps:
Physics colliders are now generated with the correct geometry and position for isometric maps. - Clear Distinction Between
grid_sizeandtile_size:
Previously,tile_size(the actual size of a tile) andgrid_size(the space a tile occupies on the grid) were treated as equivalent. This is not always true, especially for isometric maps. The API now enforces a clear distinction. - API Renaming for Clarity:
Several functions and methods have been renamed to improve clarity and expressiveness.
Migration steps
-
Update the dependency in
Cargo.toml:bevy_ecs_tiled = "0.9" -
Adjust function usage:
-
Removed:
tile_size_from_grid_size()has been removed.
Reason: Avoids confusion betweentile_sizeandgrid_size.tile_size_from_map()has been removed.
Reason: You should useTiledMapAsset::largest_tile_sizeinstead. -
Added:
A newtile_size()helper function is available to retrieve thetile_sizefrom aTile. -
Changed:
TiledMapAsset::world_space_from_tiled_position()is now private to the crate.
Reason: This is a low-level function and should not be used directly.TiledMapAsset::object_world_position()→ Renamed toTiledMapAsset::object_relative_position()
Signature remains the same.TiledMapAsset::tile_world_position()→ Renamed toTiledMapAsset::tile_relative_position()
Now takes an extraTilemapTileSizeargument instead of relying on the map’sTilemapGridSize.
-
Updated Geometry Methods:
The following methods onTiledObjectnow take 4 additional arguments to properly handle isometric maps:center()vertices()line_string()polygon()
Resources
Migration to bevy_ecs_tiled v0.8
This guide outlines the steps required to migrate your project to version 0.8 of bevy_ecs_tiled.
Main Changes
- Improved
TiledEventAPI: Provides an unified way to handle events and access underlying Tiled data. - Attach shape information to
TiledObject: Direct access to Tiled objects shape information through ECS. - Reworked physics colliders spawning: Integrate with the
geocrate to define and aggregate colliders together. - Reworked name filter API: The filter API have been extended to use
regexand is now also used for selecting which types are exported as Tiled custom properties. - Simplify
TiledMapStorageusage: Add helpers functions to theTiledMapStoragecomponent so it’s easier to work with. - Explicit
SystemSet: Allow precise systems ordering for user applications. - Rationalize naming: Several types or functions have been renamed to better reflect what they actually do.
- Source code re-organization: Several files have been moved around or renamed.
Migration Steps
-
Update the dependency in
Cargo.toml:bevy_ecs_tiled = "0.8" -
Adjust your types:
Some types have been renamed, without any functional change, or not much.
It should be safe to simply run a “search and replace” command, in the following order (make sure to match whole words):
Old name New name Functional changes ? TiledMapTiledMapAssetTiledWorldTiledWorldAssetTiledMapHandleTiledMapTiledWorldHandleTiledWorldTiledMapPluginTiledPluginTiledColliderSpawnInfosThis one was actually removed TiledMapMarkerTiledMapThis one was actually removed TiledWorldMarkerTiledWorldThis one was actually removed TiledMapLayerTiledLayerTiledLayernow holds the layer kindTiledMapTileLayerTiledLayerTiledLayernow holds the layer kindTiledMapObjectLayerTiledLayerTiledLayernow holds the layer kindTiledMapGroupLayerTiledLayerTiledLayernow holds the layer kindTiledMapImageLayerTiledLayerTiledLayernow holds the layer kindTiledMapTileLayerForTilesetTiledTilemapTiledMapTileTiledTileTiledMapObjectTiledObjectTiledMapImageTiledImage -
Adjust your functions:
Some functions have been renamed, without changing their behaviour, or not much.
It should be safe to simply run a “search and replace” command:
Old name New name get_map_typetilemap_type_from_mapget_grid_sizegrid_size_from_mapget_tile_sizetile_size_from_maptile_size_from_gridtile_size_from_grid_sizeThe following functions are now methods of the
TiledMapAssetstruct:for_each_tileworld_space_from_tiled_position(renamed fromfrom_tiled_position_to_world_space)
-
Adjust your imports:
Some modules or types have changed names or locations. If you import types using their defining path you may need to adjust.
An easy way to get past this is to import the whole prelude:
bevy_ecs_tiled::prelude::*or to use the type prelude path, such asbevy_ecs_tiled::prelude::TiledPlugin. -
Adjust
EventAPI usageThe event API has been reworked and now revolves around a generic
TiledEvent<E>structure. This provides more context for each event, including the origin of each particular eventEand helper methods to access Tiled data.See the dedicated guide on events for details.
-
Update custom physics backend
Most of the work that was done in the physics backend is now done by the crate itself which should simplify any custom physics backend implementation. As a result, the
spawn_collidersfunction from theTiledPhysicsBackendtrait have changed: you should refer to its documentation for more information. -
Update filter API usage
The filter API used to revolve around two enums:
TiledNamefor creating filters andTiledNameFilterfor matching them. It felt a bit cumbersome.
Now, everything is done via the newTiledFilterenum for doing both operations and we added support for regular expresions using theregexcrate.We also added a new parameter to
TiledPluginConfigto control which properties are exported from Bevy at startup. -
Adjust
TiledMapStoragecomponent usageFields in
TiledMapStorageare now private. You should use the provided methods instead of accessing fields directly.
Resources
From v0.6.X to v0.7.X
Overview
Version 0.7 updates the crate for Bevy v0.16 and take advantage of the new TilemapAnchor component from bevy_ecs_tilemap.
Bevy v0.16 update
TilemapAnchor
The TiledMapAnchor component have been deprecated in favor of the TilemapAnchor component from bevy_ecs_tilemap.
This new enum contains more variants, as you can see in the API reference.
Before :
#![allow(unused)]
fn main() {
commands.spawn((
TiledMapHandle(asset_server.load("map.tmx")),
TiledMapAnchor::Center,
));
}
After :
#![allow(unused)]
fn main() {
commands.spawn((
TiledMapHandle(asset_server.load("map.tmx")),
TilemapAnchor::Center,
));
}
From v0.5.X to v0.6.X
Overview
Version 0.6 brings new features such as Tiled world support and tiles colliders aggregation (which should improve performances when working with physics), bugfixes (mostly for infinite maps) and a rework of the API to make it more user-friendly.
For instance, we now use entity-scoped observers for our loading events instead of global ones, so it’s easier to work with several maps at the same time.
Code base have also been re-organized to better fit the new world feature, but it should not impact end-users.
Plugin instanciation
You don’t need to manually instanciate the TilemapPlugin from bevy_ecs_tilemap.
It is now automatically done when adding TiledMapPlugin to your application if not already done.
Before :
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use bevy_ecs_tilemap::prelude::*;
fn main() {
App::new()
// Main plugin from bevy_ecs_tilemap
.add_plugins(TilemapPlugin)
// Main plugin from bevy_ecs_tiled
.add_plugins(TiledMapPlugin::default());
}
After :
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
// Main plugin from bevy_ecs_tiled:
// implicitely load bevy_ecs_tilemap main plugin
.add_plugins(TiledMapPlugin::default());
}
Map loading events
Map loading events have been heavily updated :
- Instead of using a single global observer, we now trigger an entity-scoped observer and send a regular event
- Only use “safe” methods to retrieve data from events (no more
unwrap()internally) - Store an
AssetId<TiledMap>instead of aHandle<TiledMap>to acces Tiled map data, enforce the fact that we store a weak reference in the event and not a strong one. - Some fields from the events have been renamed
Before :
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledMapPlugin::default())
.add_systems(Startup, startup)
// Previously, we could only use a global observer
.add_observer(|trigger: Trigger<TiledMapCreated>, map_asset: Res<Assets<TiledMap>>| {
// Previously, the method to retrieve map data would panic in case of error
let map = trigger.event().map(&map_asset);
info!("(observer) Loaded map: {:?}", map);
});
}
fn startup(
mut commands: Commands,
asset_server: Res<AssetServer>
) {
commands.spawn(TiledMapHandle(asset_server.load("map.tmx")));
}
After :
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
.add_plugins(TiledMapPlugin::default())
.add_systems(Startup, startup)
.add_systems(Update, read_map_events);
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands
.spawn(TiledMapHandle(asset_server.load("map.tmx")))
// Now, you can use an entity-scoped observer
.observe(
|trigger: Trigger<TiledMapCreated>, map_asset: Res<Assets<TiledMap>>| {
// Now, this method return an Option<T> and don't panic in case of error
if let Some(map) = trigger.event().get_map(&map_asset) {
info!("(observer) Loaded map: {:?}", map);
}
},
);
}
// Or a regular event
fn read_map_events(mut map_events: EventReader<TiledMapCreated>, map_asset: Res<Assets<TiledMap>>) {
for event in map_events.read() {
if let Some(map) = event.get_map(&map_asset) {
info!("(event) Loaded map: {:?}", map);
}
}
}
For more detailled informations, you should have a look to the dedicated example or the guide.
Physics
To get tile colliders aggregation working, we had to rework a bit the physics API :
- function
TiledPhysicsBackend::spawn_collider()can now spawn several colliders per call. To reflect that it now returns aVec<TiledColliderSpawnInfos>instead of anOption<TiledColliderSpawnInfos>. Also, it now takes aTiledNameFilteras input parameter to filter out unwanted objects - remove the
TiledColliderCreatedevents which added some complexity but did not have actual usage - rename
TiledColliderSourceTypetoTiledColliderand remove theTilevariant in favor of the newTilesLayer TiledPhysicsBackendnow requires to implement theClone,ReflectandDebugtraits- rename Rename
ObjectNameFiltertoTiledNameFiltersince we also use it for layer name
Schedules
To prevent potential Bevy error B0003 we changed a bit how our systems are scheduled.
Before, everything was done in the Update schedule.
Now, we schedule systems that spawn entities in the PreUpdate schedule and systems that could despawn entities in the PostUpdate schedule.
Misc API changes
- rename
TiledIdStoragecomponent toTiledMapStorageso we are consistent with the new world API - rename
ObjectNameFiltertype toTiledNameFiltersince we also use it for layer names - rename
from_tiled_coords_to_bevyfunction tofrom_tiled_position_to_world_space - split
TiledMapSettingscomponent in two:TiledMapAnchorandTiledMapLayerZOffset
From v0.4.X to v0.5.X
Overview
Version 0.5 updates the crate for Bevy v0.15.
It notably takes advantage of the new required_component feature to simplify the crate API.
Also, this version provide some fixes related to user properties. If you are using them, you should reload your export file.
Bevy v0.15 update
Misc changes
TiledMapSettings update
map_initial_transform and map_initial_visibility have been removed from TiledMapSettings.
If you want to tweak your map positioning or visibility, you should instead directly insert corresponding Transform or Visibility components on the map entity.
Before:
#![allow(unused)]
fn main() {
let map_handle: Handle<TiledMap> = asset_server.load("map.tmx");
commands.spawn((
TiledMapHandle(map_handle),
TiledMapSettings {
map_initial_transform: Transform::from_xyz(150., 100., 0.),
map_initial_visibility: Visibility::Hidden,
..Default::default()
},
));
}
After:
#![allow(unused)]
fn main() {
let map_handle: Handle<TiledMap> = asset_server.load("map.tmx");
commands.spawn((
TiledMapHandle(map_handle),
Transform::from_xyz(150., 100., 0.),
Visibility::Hidden,
));
}
From v0.3.X to v0.4.X
Overview
Version 0.4 was initially motivated by an update to the way we handle user properties but ended as a major overhaul of the plugin to provide a better API and to give more control to the user.
Plugin instanciation
The plugin now has an associated configuration, which you need to provide when you add it to your application.
The easiest way is to use the default configuration value :
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn main() {
App::new()
// You still need the bevy_ecs_tilemap plugin
.add_plugins(TilemapPlugin)
// And now, you have to provide a configuration for bevy_ecs_tiled plugin
.add_plugins(TiledMapPlugin::default())
.run();
}
The plugin configuration is described in the API reference
Tiled map spawn and configuration
The plugin entry point, ie. the TiledMapBundle bundle is gone.
It was cumbersome and did not allow for a proper separation of concerns (for instance, for physics).
Also, the Handle<TiledMap> type is not a Bevy component anymore.
It was done in order to anticipate expected changes in Bevy where Handle<T> won’t be able to derive the Component trait anymore.
Anyway, the new way to spawn a map is now easier: you just have to spawn a TiledMapHandle referencing your .TMX file asset:
#![allow(unused)]
fn main() {
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Load the map: ensure any tile / tileset paths are relative to assets/ folder
let map_handle: Handle<TiledMap> = asset_server.load("map.tmx");
// Spawn the map with default options
commands.spawn(TiledMapHandle(map_handle));
}
}
You can customize various settings about how to load the map by inserting the TiledMapSettings component on the map entity.
Tiled user properties
Before this change, you had to define your custom types both in Tiled and in your rust code. It was not user-friendly and error-prone.
Now, we take advantage of bevy_reflect to generate a file containing all the types known to Bevy.
This file can be imported in Tiled so you can use these types directly in the editor.
Migrating from the old implementation should be straight-forward.
First, you need need to update your custom types so they actually implement the Reflect trait :
- remove
#[derive(TiledObject)],#[derive(TiledCustomTile)],#[derive(TiledClass)]and#[derive(TiledEnum)]derived traits. Make sure to also remove associated attributes. - add
#[derive(Reflect)]derive trait on the types you want to use in Tiled. - make sure your components have the
#[reflect(Component)]attribute
Then, in your main / in your plugin setup, you then need to register your types with Bevy :
- replace calls to
register_tiled_object::<T>()with calls toregister_type::<T>(). - replace calls to
register_tiled_custom_tile::<T>()with calls toregister_type::<T>().
The final step is to actually generate the types import file (run your game once) and import the types to Tiled. Note that you may have to update your map / your tilesets to use the new types you just imported.
A dedicated guide about how to setup user properties is available in this book.
Tiled physics
Eventhough functionnalities around physics did not change much, the internals have been completely reworked and the API was updated a bit.
Notably, now you need to instanciate another plugin and specify which physics backend you want to use. The physics section of the book should get you through.
Map events
This is a new feature of this version which gives more control to the user over what he wants to do with a Tiled map. More information in the dedicated section
Misc changes
enum MapPositioning
Both enum name and fields name have been updated to better reflect what they actually do.
You should now use the new LayerPositioning enum.
fn from_isometric_coords_to_bevy()
Parameters tiled_position: Vec2 and iso_coords: IsoCoordSystem have been swapped for better consistency with other utility functions.
Useful links
Here is an unordered list of useful resources that may help when working on a 2D tile-base game.
Feel free to suggest any other link!
Notable crates
bevy: the Bevy enginebevy_ecs_tilemap: the crate we use for rendering our tilesrs-tiled: official Tiled rust bindingsbevy_ecs_ldtk: an equivalent ofbevy_ecs_tiledbut for the LDTK map editorhexx: an hexagonal tools lib for stuff like path-finding or hex coordinates manipulationbevy_mod_picking: a flexible set of plugins that add picking functionality to your bevy appbevy_picking_tilemap: provides abevy_mod_pickingbackend to add integration withbevy_ecs_tilemap, enabling individual Tile entities to receive the picking eventsavian: Avian physic backendbevy_rapier: Rapier physic backendbevy_northstar: A 2D/3D pathfinding crate, with a concrete usage example withbevy_ecs_tiled
Notable resources
- Bevy official website: lots of examples and learning materials
- Bevy API reference
- Unofficial Bevy Cheat Book: one the best resource to learn Bevy
- Tiled official website: to get the latest Tiled version and read associated documentation
- Red Blob Games: collections of tutorials on various gamedev topics, especially the hexagonal grids reference
- Some maths regarding isometric tiles
Contributing
Thank you for your interest in contributing to bevy_ecs_tiled!
Whether you’re fixing bugs, adding features, improving documentation, or helping other users, your contributions are greatly appreciated.
Where to Start
If you’re unsure where to begin, check out the GitHub issues page. You might find it helpful to look at issues:
If you feel you can tackle one of these, please feel free to submit a PR!
Other valuable ways to contribute include:
- Helping other users by responding to issues or reviewing PRs
- Reporting bugs or suggesting improvements by opening new issues
- Contributing to dependencies, such as
rs-tiled,bevy_ecs_tilemap, or other crates in the Bevy ecosystem (or Bevy itself!)
Contribution Guidelines
When submitting a pull request, please ensure that:
- CI passes:
Run
just checklocally to check formatting, linting, and tests. - Documentation: Add or update in-code documentation for any new features or changes.
- Changelog:
Update the
CHANGELOG.mdfile with a description of your fix or feature. - Examples:
If you add a new example:
- Update
examples/README.mdwith a description of your example. - Add your example to the workspace
Cargo.toml(and specify any required features).
- Update
- Assets:
If you add a new map, update
assets/README.mdwith its characteristics. If you add a new asset, update the “Assets credits” section of the mainREADME.mdand ensure you have the right to use it.
If you’re not sure about something, feel free to open a draft PR or ask questions in your issue or PR.
Manual Checks
Some behaviors cannot be checked by automated tests and must be checked manually.
Tiles Rendering
Tests run without a renderer: they check that tiles are added to or removed from their tilemap TileStorage, but not what is actually drawn.
However, how a tile is drawn after it has been modified relies on bevy_ecs_tilemap internals: to make sure a moved or replaced tile is removed from its previous location, its TilePos component is removed then inserted again (see sync_tiles in src/tiled/tile.rs).
When changing tiles rendering code, when upgrading bevy_ecs_tilemap and before each release, run the map_dynamic example with physics colliders displayed:
cargo run --example map_dynamic --features avian
Then check that rendering and colliders always match:
[1](despawn a tile): the tile and its collider disappear.[2](change a tile): the tile texture changes and its collider follows the new tile shape.[3](move a tile), several times in a row: the tile is drawn at its new position only, along with its collider. Also move a tile onto another one, then away: the tile it replaced is neither drawn nor has a collider anymore.[4](spawn a tile): the new tile is drawn, along with its collider.[5]and[6](despawn an object, change an object shape): the object collider follows.[R](reload the map): the map is back to its initial state.
Performance
A performance test measures, on a large map, the time needed to spawn, modify and despawn its tiles and objects. It is ignored by default: run it in release mode to compare performance before and after a change.
cargo test --release --all-features --lib perf -- --ignored --nocapture
Each scenario is run several times (5 by default, or the value of the PERF_RUNS environment variable): the test prints the median and minimum duration of a frame, along with the time spent spawning map data and in the SyncTiles, SyncRender and SyncPhysics system sets.
Measures can vary significantly from one run to another: when comparing two versions, alternate their runs rather than comparing runs made at different times.
Thanks in advance for helping make bevy_ecs_tiled better!