Trouv / bevy_ecs_ldtk

ECS-friendly ldtk plugin for bevy, leveraging bevy_ecs_tilemap
Other
641 stars 73 forks source link

`LdtkFields` trait for easily accessing field instances #175

Closed Trouv closed 1 year ago

Trouv commented 1 year ago

It should be easier to access field instances on entities and levels and having them be your desired type. We can add some extension methods to the Level and EntityInstances (and maybe a future LevelMetadata type) that allows getting a field instance by name and expected type - providing an error otherwise. Doing this via trait would make it easy to maintain, as we could keep the logic out of the quicktype-generated ldtk module, and leave most of it to default implementation. Something like...

pub trait LdtkFields {
    fn field_instances(&self) -> &[FieldInstance];

    fn get_field_instance(&self, identifier: String) -> Result<&FieldInstance> {
        self.field_instances().iter().find(|f| f.identifier == identifier).ok_or(todo!())
    }

    fn get_field(&self, identifier: String) -> Result<&FieldValue> {
        Ok(self.get_field_instance(identifier)?.value)
    }

    fn get_maybe_int_field(&self, identifier: String) -> Result<Option<i32>> {
        if let FieldValue::Int(maybe_int) = self.get_field(identifier)? {
            Ok(maybe_int)
        } else {
            Err(todo!())
        }
    }

    fn get_int_field(&self, identifier: String) -> Result<i32> {
        if let Some(int) = self.get_maybe_int_field(identifier)? {
            Ok(int)
        } else {
            Err(todo!())
        }
    }

    // implement similar methods for all `FieldValue` variants...
}