ui_texture_atlas/
ui_texture_atlas.rs1use bevy::{color::palettes::css::*, prelude::*};
4
5fn main() {
6 App::new()
7 .add_plugins(DefaultPlugins.set(
8 ImagePlugin::default_nearest(),
12 ))
13 .add_systems(Startup, setup)
14 .add_systems(Update, increment_atlas_index)
15 .run();
16}
17
18fn setup(
19 mut commands: Commands,
20 asset_server: Res<AssetServer>,
21 mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
22) {
23 commands.spawn(Camera2d);
25
26 let font_size: f32 = 20.;
27 let text_font = TextFont::from_font_size(20.);
28
29 let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
30 let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None);
31 let texture_atlas_handle = texture_atlases.add(texture_atlas);
32
33 commands
35 .spawn(Node {
36 width: percent(100),
37 height: percent(100),
38 flex_direction: FlexDirection::Column,
39 justify_content: JustifyContent::Center,
40 align_items: AlignItems::Center,
41 row_gap: px(font_size * 2.),
42 ..default()
43 })
44 .with_children(|parent| {
45 parent.spawn((
46 ImageNode::from_atlas_image(
47 texture_handle,
48 TextureAtlas::from(texture_atlas_handle),
49 ),
50 Node {
51 width: px(256),
52 height: px(256),
53 ..default()
54 },
55 BackgroundColor(ANTIQUE_WHITE.into()),
56 Outline::new(px(8), Val::ZERO, CRIMSON.into()),
57 ));
58 parent
59 .spawn((Text::new("press "), text_font.clone()))
60 .with_child((
61 TextSpan::new("space"),
62 TextColor(YELLOW.into()),
63 text_font.clone(),
64 ))
65 .with_child((TextSpan::new(" to advance frames"), text_font));
66 });
67}
68
69fn increment_atlas_index(
70 mut image_nodes: Query<&mut ImageNode>,
71 keyboard: Res<ButtonInput<KeyCode>>,
72) {
73 if keyboard.just_pressed(KeyCode::Space) {
74 for mut image_node in &mut image_nodes {
75 if let Some(atlas) = &mut image_node.texture_atlas {
76 atlas.index = (atlas.index + 1) % 6;
77 }
78 }
79 }
80}