LDtk allows entities to point to other entities using a field.
This is analogous to a bevy "relation" - a component on one entity that stores the Entity identifier of another entity.
This chapter goes through one possible method for resolving LDtk entity references as such.
This code is used in the field_instances cargo example, and facilitates "enemy" entities pointing to another "enemy" entity as their "mother".
First, create a component representing an "unresolved" entity reference, storing the target entity's LDtk iid rather than a bevy Entity:
#![allow(unused)]fnmain() {
use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;
#[derive(Debug, Default, Deref, DerefMut, Component)]pubstructUnresolvedMotherRef(Option<EntityIid>);
}
Create a method for constructing this component from an &EntityInstance.
This should retrieve the value of the entity reference field instance on the LDtk entity.
Most likely, you'll use a hard-coded field identifier ("mother" in this example) to find it:
#![allow(unused)]fnmain() {
use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;
pubstructUnresolvedMotherRef(Option<EntityIid>);
impl UnresolvedMotherRef {
pubfnfrom_mother_field(entity_instance: &EntityInstance) -> UnresolvedMotherRef {
UnresolvedMotherRef(
entity_instance
.get_maybe_entity_ref_field("mother")
.expect("expected entity to have mother entity ref field")
.as_ref()
.map(|entity_ref| EntityIid::new(entity_ref.entity_iid.clone())),
)
}
}
}
Add this component to the LdtkEntity and configure it to be constructed using this method.
This guide assumes that you've already registered this bundle to the app.
Create a second relational component that stores the actual bevy Entity that this Unresolved reference should "resolve" to.
#![allow(unused)]fnmain() {
use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;
#[derive(Debug, Deref, DerefMut, Component, Reflect)]pubstructMother(Entity);
}
Finally, create a "post-processing" system that takes entities with the Unresolved component, finds the entity with the matching EntityIid, and replaces the Unresolved component with the relational component.