Texture atlases and sprite animation
Draw frames of a sprite sheet with TextureAtlas and TextureAtlasLayout, build atlases from separate images, and animate sprites frame by frame.
On this page
A texture atlas is one image that holds many smaller ones, such as every frame of a character's run cycle. Drawing from one atlas is cheaper than switching between many images, and it's how you animate sprites frame by frame.
An atlas has two parts:
| Type | What it is |
|---|---|
TextureAtlasLayout | An asset listing the rectangle of each frame inside the image. |
TextureAtlas { layout, index } | Goes in a Sprite (or a UI ImageNode): which layout to use and which frame to draw. |
Use a sprite sheet#
When the frames sit on a regular grid, describe the grid with TextureAtlasLayout::from_grid(tile_size, columns, rows, padding, offset). Frames are numbered left to right, top to bottom, from 0.
use neo::prelude::*;
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
let texture = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
// 7 frames of 24×24 pixels in one row
let layout = layouts.add(TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None));
commands.spawn(Camera2d);
commands.spawn((
Sprite::from_atlas_image(texture, TextureAtlas { layout, index: 1 }),
Transform::from_scale(Vec3::splat(6.0)),
));
}Use padding when frames have gaps between them and offset when the grid doesn't start at the top-left corner. For frames of different sizes, start with TextureAtlasLayout::new_empty(size) and call add_texture(URect) for each one.
Animate a sprite#
Change index over time. A Timer keeps the frame rate independent of the game's frame rate:
#[derive(Component)]
struct AnimationIndices {
first: usize,
last: usize,
}
#[derive(Component, Deref, DerefMut)]
struct AnimationTimer(Timer);
fn animate_sprite(
time: Res<Time>,
mut query: Query<(&AnimationIndices, &mut AnimationTimer, &mut Sprite)>,
) {
for (indices, mut timer, mut sprite) in &mut query {
timer.tick(time.delta());
if timer.just_finished()
&& let Some(atlas) = &mut sprite.texture_atlas
{
atlas.index = if atlas.index == indices.last { indices.first } else { atlas.index + 1 };
}
}
}Spawn the sprite with AnimationIndices { first: 1, last: 6 } and AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), and add animate_sprite to Update. For an animation that plays once when something happens, use a TimerMode::Once timer and reset it when you trigger the animation, as the sprite_animation example does. Timers are covered in Time.
Build an atlas at runtime#
TextureAtlasBuilder packs separately loaded images into one atlas image. Load the images first (for example with asset_server.load_folder), wait until they're loaded, then build:
fn build_atlas(folder: &LoadedFolder, textures: &mut Assets<Image>) -> (TextureAtlasLayout, TextureAtlasSources, Handle<Image>) {
let mut builder = TextureAtlasBuilder::default();
builder.padding(UVec2::splat(2));
for handle in folder.handles.iter() {
let id = handle.id().typed_unchecked::<Image>();
if let Some(texture) = textures.get(id) {
builder.add_texture(Some(id), texture);
}
}
let (layout, sources, image) = builder.build().unwrap();
(layout, sources, textures.add(image))
}TextureAtlasSources maps each original image to its frame: sources.handle(layout_handle, &original_image) returns the TextureAtlas to put in a sprite. Padding between frames stops neighbouring frames bleeding into each other when the atlas is filtered.
Atlases in UI#
ImageNode::from_atlas_image(image, atlas) draws an atlas frame in a UI node, and its texture_atlas field works the same way. See Images and styling.
Examples#
| Example | What it shows |
|---|---|
sprite_sheet | A looping animation from a grid sheet. |
sprite_animation | Animations triggered by keys, at different frame rates. |
texture_atlas | Building atlases from a folder of images, with and without padding. |
ui_texture_atlas | An atlas frame in a UI node. |
Run one from the engine core's workspace: cargo run --example sprite_sheet.