Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ui/ui_texture_atlas.rs
6595 views
1
//! This example illustrates how to use `TextureAtlases` within ui
2
3
use bevy::{color::palettes::css::*, prelude::*};
4
5
fn main() {
6
App::new()
7
.add_plugins(DefaultPlugins.set(
8
// This sets image filtering to nearest
9
// This is done to prevent textures with low resolution (e.g. pixel art) from being blurred
10
// by linear filtering.
11
ImagePlugin::default_nearest(),
12
))
13
.add_systems(Startup, setup)
14
.add_systems(Update, increment_atlas_index)
15
.run();
16
}
17
18
fn setup(
19
mut commands: Commands,
20
asset_server: Res<AssetServer>,
21
mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
22
) {
23
// Camera
24
commands.spawn(Camera2d);
25
26
let text_font = TextFont::default();
27
28
let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
29
let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None);
30
let texture_atlas_handle = texture_atlases.add(texture_atlas);
31
32
// root node
33
commands
34
.spawn(Node {
35
width: percent(100),
36
height: percent(100),
37
flex_direction: FlexDirection::Column,
38
justify_content: JustifyContent::Center,
39
align_items: AlignItems::Center,
40
row_gap: px(text_font.font_size * 2.),
41
..default()
42
})
43
.with_children(|parent| {
44
parent.spawn((
45
ImageNode::from_atlas_image(
46
texture_handle,
47
TextureAtlas::from(texture_atlas_handle),
48
),
49
Node {
50
width: px(256),
51
height: px(256),
52
..default()
53
},
54
BackgroundColor(ANTIQUE_WHITE.into()),
55
Outline::new(px(8), Val::ZERO, CRIMSON.into()),
56
));
57
parent
58
.spawn((Text::new("press "), text_font.clone()))
59
.with_child((
60
TextSpan::new("space"),
61
TextColor(YELLOW.into()),
62
text_font.clone(),
63
))
64
.with_child((TextSpan::new(" to advance frames"), text_font));
65
});
66
}
67
68
fn increment_atlas_index(
69
mut image_nodes: Query<&mut ImageNode>,
70
keyboard: Res<ButtonInput<KeyCode>>,
71
) {
72
if keyboard.just_pressed(KeyCode::Space) {
73
for mut image_node in &mut image_nodes {
74
if let Some(atlas) = &mut image_node.texture_atlas {
75
atlas.index = (atlas.index + 1) % 6;
76
}
77
}
78
}
79
}
80
81