Skip to content

Getting a sprite from a spritesheet by region (position, size) #5981

Answered by ickshonpe
Mo32167 asked this question in Q&A
Discussion options

You must be logged in to vote

You can add new sprite rects to a TextureAtlas manually with the add_texture method.
It takes a rectangular area of the image as an argument and then returns an index you can use to spawn a SpriteSheetBundle.
For your example, you could do:

// atlases is a ResMut<Assets<TextureAtlas> and assumes we've got a handle for the atlas
if let Some(breakout_atlas) = atlases.get_mut(&break_out_atlas_handle) {
  let red_ball_index = breakout_atlas.add_texture(bevy_sprite::Rect { min: vec2(32., 0.), max: vec2(64.0, 32.0) });
  commands.spawn_bundle(SpriteSheetBundle {
      sprite: TextureAtlasSprite::new(red_ball_index),
      texture_atlas: breakout_atlas_handle.clone(),
      ..Default::default()
  }

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@Mo32167
Comment options

@ickshonpe
Comment options

Answer selected by Mo32167
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants