Log in to access Rust Adventure videos!

Lesson Details

The Text for the point values on the tiles is set up, but it isn't showing in the tiles yet. This is because we haven't loaded a font using the asset server.

We'll choose to do the same thing we did for initializing the Materials resource. Create a new struct called FontSpec with a field named family that will hold a Handle to a Bevy Font.

The implementation of the FromWorld trait for FontSpec is how we'll initialize our font loading.

We need access to the AssetServer and we can use get_resource_mut to get it.

Finally, we can use the asset_server.load() to load a font file.

struct FontSpec {
    family: Handle<Font>,
}

impl FromWorld for FontSpec {
    fn from_world(world: &mut World) -> Self {
        let asset_server = world
            .get_resource_mut::<AssetServer>()
            .unwrap();
        FontSpec {
            family: asset_server
                .load("fonts/FiraSans-Bold.ttf"),
        }
    }
}

To make it easy, we'll follow what Bevy does in their own examples and use the Fira Sans font family. We can grab the ttf from the bevy repo and put it in assets/fonts/ folder. The assets folder sits at the root of our project and the AssetServer looks here for the fonts folder.

Now that we have FontSpec set up, we can initialize it by using

.init_resource::<FontSpec>()

The spawn_tiles system will need to request the FontSpec resource.

fn spawn_tiles(
    mut commands: Commands,
    materials: Res<Materials>,
    query_board: Query<&Board>,
    font_spec: Res<FontSpec>,
) {...}

at which point we can use it in the same way we used the Materials colors, by cloning the FontSpec.family Handle.

TextStyle {
    font: font_spec
        .family
        .clone(),
    font_size: 40.0,
    color: Color::BLACK,
    ..Default::default()
},

The will display 2 in each box for us.

end result