Skip to content

Commit

Permalink
Use new m tag for dynamic example
Browse files Browse the repository at this point in the history
  • Loading branch information
TimJentzsch committed Jul 22, 2024
1 parent 39faa50 commit 7968614
Showing 1 changed file with 20 additions and 23 deletions.
43 changes: 20 additions & 23 deletions examples/dynamic.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
//! This example demonstrates how parts of the text can be efficiently updated dynamically.
//! To do this, we use the special `[m]` tag, which allows us to assign a marker component to the contained text.
//! We can then query for the marker component as usual and apply our edits.

use bevy::prelude::*;
use bevy_mod_bbcode::{Bbcode, BbcodeBundle, BbcodePlugin, BbcodeSettings};
use bevy_mod_bbcode::{BbcodeBundle, BbcodePlugin, BbcodeSettings};

#[derive(Debug, Component)]
struct Marker;
#[derive(Component, Clone)]
struct TimeMarker;

fn main() {
App::new()
Expand All @@ -15,27 +19,20 @@ fn main() {
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());

commands.spawn((
BbcodeBundle::from_content(
// The text will be added later
"",
BbcodeSettings::new(40., Color::WHITE)
.with_regular_font(asset_server.load("fonts/FiraSans-Regular.ttf"))
.with_bold_font(asset_server.load("fonts/FiraSans-Bold.ttf"))
.with_italic_font(asset_server.load("fonts/FiraSans-Italic.ttf")),
),
Marker,
commands.spawn(BbcodeBundle::from_content(
"Time passed: [m=time]0.0[/m] s",
BbcodeSettings::new(40., Color::WHITE)
.with_regular_font(asset_server.load("fonts/FiraSans-Regular.ttf"))
.with_bold_font(asset_server.load("fonts/FiraSans-Bold.ttf"))
.with_italic_font(asset_server.load("fonts/FiraSans-Italic.ttf"))
// Register the marker component for the `m=time` tag
.with_marker("time", TimeMarker),
));
}

fn update(time: Res<Time>, mut query: Query<(&mut Bbcode, &mut BbcodeSettings), With<Marker>>) {
let (mut bbcode, mut settings) = query.single_mut();

// Dynamically change the text to the elapsed time
bbcode.content = format!(
"Time passed: [b][c=#ffffff]{:.2}[/c][/b]",
time.elapsed_seconds()
);
// Dynamically change the default text color
settings.color = Hsla::hsl((time.elapsed_seconds() * 20.) % 360., 1., 0.7).into();
fn update(time: Res<Time>, mut query: Query<&mut Text, With<TimeMarker>>) {
for mut text in query.iter_mut() {
// We can directly query for the `Text` component and update it, without the BBCode being parsed again
text.sections[0].value = format!("{:.0}", time.elapsed_seconds());
}
}

0 comments on commit 7968614

Please sign in to comment.