Skip to content

Commit

Permalink
Add a way to specify padding/ margins between sprites in a TextureAtl…
Browse files Browse the repository at this point in the history
…as. (bevyengine#460)

Add a way to specify padding between sprites in a TextureAtlas
  • Loading branch information
sY9sE33 authored and joshuajbouw committed Oct 24, 2020
1 parent 4485f5b commit e28e7ef
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 12 deletions.
47 changes: 37 additions & 10 deletions crates/bevy_sprite/src/texture_atlas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,29 +63,56 @@ impl TextureAtlas {
}

/// Generate a `TextureAtlas` by splitting a texture into a grid where each
/// cell of the grid is one of the textures in the atlas
/// cell of the grid of `tile_size` is one of the textures in the atlas
pub fn from_grid(
texture: Handle<Texture>,
size: Vec2,
tile_size: Vec2,
columns: usize,
rows: usize,
) -> TextureAtlas {
let texture_width = size.x() / columns as f32;
let texture_height = size.y() / rows as f32;
Self::from_grid_with_padding(texture, tile_size, columns, rows, Vec2::new(0f32, 0f32))
}

/// Generate a `TextureAtlas` by splitting a texture into a grid where each
/// cell of the grid of `tile_size` is one of the textures in the atlas and is separated by
/// some `padding` in the texture
pub fn from_grid_with_padding(
texture: Handle<Texture>,
tile_size: Vec2,
columns: usize,
rows: usize,
padding: Vec2,
) -> TextureAtlas {
let mut sprites = Vec::new();
let mut x_padding = 0.0;
let mut y_padding = 0.0;

for y in 0..rows {
if y > 0 {
y_padding = padding.y();
}
for x in 0..columns {
if x > 0 {
x_padding = padding.x();
}

let rect_min = Vec2::new(
(tile_size.x() + x_padding) * x as f32,
(tile_size.y() + y_padding) * y as f32,
);

sprites.push(Rect {
min: Vec2::new(x as f32 * texture_width, y as f32 * texture_height),
max: Vec2::new(
(x + 1) as f32 * texture_width,
(y + 1) as f32 * texture_height,
),
min: rect_min,
max: Vec2::new(rect_min.x() + tile_size.x(), rect_min.y() + tile_size.y()),
})
}
}

TextureAtlas {
size,
size: Vec2::new(
((tile_size.x() + x_padding) * columns as f32) - x_padding,
((tile_size.y() + y_padding) * rows as f32) - y_padding,
),
textures: sprites,
texture,
texture_handles: None,
Expand Down
4 changes: 2 additions & 2 deletions examples/2d/sprite_sheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ fn setup(
"assets/textures/rpg/chars/gabe/gabe-idle-run.png",
)
.unwrap();
let texture = textures.get(&texture_handle).unwrap();
let texture_atlas = TextureAtlas::from_grid(texture_handle, texture.size, 7, 1);

let texture_atlas = TextureAtlas::from_grid(texture_handle, Vec2::new(24.0, 24.0), 7, 1);
let texture_atlas_handle = texture_atlases.add(texture_atlas);
commands
.spawn(Camera2dComponents::default())
Expand Down

0 comments on commit e28e7ef

Please sign in to comment.